原文链接:https://www.jylt.cc/#/detail?id=dda55435cfa02dfbfc91729e3d3daf08
文章目录
背景
日常我们在保存图片的时候,会将图片放到服务器本地或者上传到其他服务器,然后将图片的路径放入到数据库,这样既可以减小数据库占用空间,又可以减轻数据库的操作压力。
但富文本编辑器有时候会被粘贴进来base64的图片,如果直接将这种类型的数据入库会使数据库占用空间急剧增长,很不合理。这时候我们理想的状态就是将base64图片转成图片文件存储起来,将base64地址替换为文件的实际地址。
base64转本地文件方法
/**
* base64图片转为本地文件
*
* @param baseStr base64图片地址
* @return 图片文件
*/
private static File base64ToFile (String baseStr) {
BASE64Decoder decoder = new BASE64Decoder();
try {
Base64ImgInfo base64ImgInfo = getBase64ImgInfo(baseStr);
if (base64ImgInfo == null) {
return null;
}
byte[] b = decoder.decodeBuffer(base64ImgInfo.getImgStr());
// 处理数据
for (int i = 0; i < b.length; ++i) {
if (b[i] < 0) {
b[i] += 256;
}
}
return File.createTempFile(UUID.randomUUID().toString(), base64ImgInfo.getType());
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
/**
* 获取base64图片信息
*
* @param baseStr base64字符串
* @return base64图片信息
*/
private static Base64ImgInfo getBase64ImgInfo(String baseStr) {
//允许的图片格式(可配置)
String imgType = "jpg,png,jpeg,gif";
if (!StringUtils.isEmpty(imgType)) {
String[] imgTypes = imgType.split(",");
Pattern pattern;
Matcher matcher;
String regex;
for (String v : imgTypes) {
regex = MessageFormat.format("data:image/{0};base64,", v);
pattern = Pattern.compile(regex, Pattern.CASE_INSENSITIVE);
matcher = pattern.matcher(baseStr);
if (matcher.lookingAt()) {
Base64ImgInfo base64ImgInfo = new Base64ImgInfo();
base64ImgInfo.setImgStr(matcher.replaceFirst(""));
base64ImgInfo.setType("." + v);
return base64ImgInfo;
}
}
}
return null;
}
@Data
public static class Base64ImgInfo {
/**
* 图片格式,比如.png
*/
private String type;
/**
* base64正文部分,去除前面data:image/png;base64,标识
*/
private String imgStr;
}
这样,通过调用方法base64ToFile
就可以获取到base64转换的图片文件了。