java1.8 获取本地图片转base64,base64转图片
时间: 2024-05-16 09:10:55 浏览: 95
base64,java与JavaScript实现
可以使用Java 1.8中的Base64类来实现本地图片与base64之间的转换。具体步骤如下:
1. 将本地图片转换为byte数组:
```java
File file = new File("图片路径");
BufferedInputStream inputStream = new BufferedInputStream(new FileInputStream(file));
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int len = 0;
while ((len = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, len);
}
byte[] data = outputStream.toByteArray();
```
2. 将byte数组转换为base64字符串:
```java
String base64 = Base64.getEncoder().encodeToString(data);
```
3. 将base64字符串转换为byte数组:
```java
byte[] data = Base64.getDecoder().decode(base64);
```
4. 将byte数组转换为图片并保存到本地:
```java
FileOutputStream outputStream = new FileOutputStream("保存路径");
outputStream.write(data);
outputStream.flush();
outputStream.close();
```
阅读全文