import java.io.*;
import java.util.Base64;
/**
* Base64工具类
* @Author: CcchenCoco
* @Version: V1.0 Base64Util, 2022/3/30 8:50
**/
public class Base64Util {
/**
* 图片转化成base64字符串
* @Author: CcchenCoco
* @Date: 2022/3/30 8:51
* @Param:
**/
public static String getImageBase64(String imgPath) {
// 待处理的图片
String imgFile = imgPath;
InputStream in = null;
byte[] data = null;
// 返回Base64编码过的字节数组字符串
String encode = null;
// 对字节数组Base64编码
Base64.Encoder encoder = Base64.getEncoder();
try {
// 读取图片字节数组
in = new FileInputStream(imgFile);
data = new byte[in.available()];
in.read(data);
encode = encoder.encodeToString(data);
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return encode;
}
/**
* base64字符串转化成图片
* @Author: CcchenCoco
* @Date: 2022/3/30 8:51
* @Param:
**/
public static boolean base64ToImage(String imgData, String imgFilePath) {
// 图像数据为空
if (imgData == null)
return false;
Base64.Decoder decoder = Base64.getDecoder();
OutputStream out = null;
try {
File img = new File(imgFilePath);
img.setExecutable(true);
// 文件路径不存在时创建路径
if(!img.getParentFile().exists()){
img.getParentFile().mkdirs();
}
img.createNewFile();
out = new FileOutputStream(img);
// Base64解码
byte[] b = decoder.decode(imgData);
for (int i = 0; i < b.length; ++i) {
if (b[i] < 0) {// 调整异常数据
b[i] += 256;
}
}
out.write(b);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (out != null) {
try {
out.flush();
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return true;
}
}
}