1. Base64简介
Base64是一种基于64个可打印字符来表示二进制数据的表示方法。通常用于在URL、Cookie和邮件等场景中,将二进制数据转换为字符串形式进行传输。
代码实现
public class ImageUtils {
/**
* 得到图片的Base64编码
* @param imagePath 图片路径
* @return 64编码字符串
*/
public static String imageToBase64(String imagePath) {
final Pattern BASE64_PATTERN=Pattern.compile(
"^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$");
//如果已经是64编码直接返回
if( BASE64_PATTERN.matcher(imagePath).matches()){
return imagePath;
}else {
StringBuilder base64Image = new StringBuilder();
File file = new File(imagePath);
try (FileInputStream imageInFile = new FileInputStream(file)) {
byte[] imageData = new byte[(int) file.length()];
int bytesRead;
while ((bytesRead = imageInFile.read(imageData)) != -1) {
// 每次读取到的实际字节数组长度为 bytesRead
byte[] partialData = new byte[bytesRead];
System.arraycopy(imageData, 0, partialData, 0, bytesRead);
base64Image.append(Base64.getEncoder().encodeToString(partialData));
}
} catch (IOException e) {
System.out.println("Error: " + e.getMessage());
}
return base64Image.toString();
}
}
/**
* 将前端传来的ase64编码解码
* @param imageBase64 图片的Base64编码
* @param path 存放的路径
*/
public static void imageSetBase64(String imageBase64, String path){
String[] base64Parts = imageBase64.split(",");
String base64Data = base64Parts[1]; // 实际的Base64编码数据部分
byte[] imageBytes = Base64.getDecoder().decode(base64Data);
// 现在imageBytes中存储了解码后的图像数据,可以进行存储或处理
// 下面是示例存储到文件系统的方法
try (FileOutputStream fos = new FileOutputStream(path)) {
fos.write(imageBytes);
} catch (IOException e) {
e.printStackTrace();
}
}
}