1. 背景
用户上传图片,对图片做特征提取,而特征提取服务只支持JPEG格式的base64 ,这就需要我们先把图片格式转为JPEG 格式
2. 转换工具类
2.1 引入依赖
<dependency>
<groupId>net.coobird</groupId>
<artifactId>thumbnailator</artifactId>
<version>0.4.15</version>
</dependency>
2.3 转换方法
public static String base64Handle2Jpeg(String base64Src) {
//判断是否包含 data:image/png,base64字符串 等头信息
int index = base64Src.indexOf(",");
String base64Str = base64Src;
if (index > 0) {
base64Str = base64Src.substring(index + 1);//去除头信息
try {
BufferedImage bufferedImage = base64String2BufferedImage(base64Str);
int width = bufferedImage.getWidth();
int height = bufferedImage.getHeight();
String filePath = "/tmp/"+System.currentTimeMillis()+".jpeg"; //存入临时文件
Thumbnails.of(bufferedImage)
.size(width, height)
.outputFormat("jpeg")
.toFile(filePath);
String result = imageToBase64Str(filePath); //转base64
FileUtils.deleteQuietly(new File(filePath)); //删除临时文件
return result; //返回结果
} catch (Exception e) {
e.printStackTrace();
}
}
return null;
}
public static String imageToBase64Str(String imgFile) throws Exception{
byte[] bytes = FileUtils.readFileToByteArray(new File(imgFile));
// 加密
return EncodeUtil.encodeBase64(bytes);
}