用java实现base64和图片互转的代码
时间: 2023-10-28 11:16:16 浏览: 88
Java实现图片和Base64之间的相互转化
下面是Java实现Base64和图片互转的代码:
```java
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Base64;
public class ImageBase64Util {
/**
* 将图片转换成Base64编码字符串
*
* @param imagePath 图片路径
* @return Base64编码字符串
*/
public static String imageToBase64(String imagePath) {
String base64 = null;
InputStream in = null;
try {
in = new FileInputStream(imagePath);
byte[] bytes = new byte[in.available()];
in.read(bytes);
base64 = Base64.getEncoder().encodeToString(bytes);
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
in.close();
} catch (Exception e) {
e.printStackTrace();
}
}
return base64;
}
/**
* 将Base64编码字符串转换成图片
*
* @param base64 Base64编码字符串
* @param imagePath 图片保存路径
* @return 是否保存成功
*/
public static boolean base64ToImage(String base64, String imagePath) {
boolean result = false;
OutputStream out = null;
try {
out = new FileOutputStream(imagePath);
byte[] bytes = Base64.getDecoder().decode(base64);
out.write(bytes);
result = true;
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
out.close();
} catch (Exception e) {
e.printStackTrace();
}
}
return result;
}
}
```
使用示例:
```java
public class ImageBase64UtilTest {
public static void main(String[] args) {
// 图片路径
String imagePath = "D:/test.png";
// 将图片转换成Base64编码字符串
String base64 = ImageBase64Util.imageToBase64(imagePath);
System.out.println(base64);
// 将Base64编码字符串转换成图片
String newImagePath = "D:/newtest.png";
ImageBase64Util.base64ToImage(base64, newImagePath);
}
}
```
阅读全文