上网找了好多关于图片压缩的帖子,基本上都是介绍谷歌Thumbnails和阿里simpleimage,自己写的也有,但我觉得还是大厂的成熟技术比较稳定,最后选择了Thumbnails。简介可参考https://www.xuebuyuan.com/3229489.html
当前项目存在历史数据,而我又比较懒不想处理了,因而当前方案需要兼容历史数据,原来图片的命名方式是uuid+后缀,因此处理完的图片名称还是uuid+后缀,原图文件名称是uuid+"-initial"+后缀,图片超过200k处理。
// 取UUID作为文件名
String uuid = CommonUtil.getUUID().replaceAll("-", "");
//fileExt文件后缀
String fileRelativePath= new StringBuffer(relativePath).append(uuid).append(fileExt).toString();
String filePath = new StringBuffer(basePath).append(fileRelativePath).toString();
String imgInitialRelativePath= new StringBuffer(relativePath).append(uuid)
.append("-initial").append(fileExt).toString();
String imgPath = new StringBuffer(basePath).append(imgInitialRelativePath).toString();
//保存原文件
File file = new File(filePath);
fileItem.write(file);
Pattern reg = Pattern.compile("[\\.](jpg|png|jpeg|gif|JPG|PNG|JPEG|GIF)$");
Matcher matcher = reg.matcher(fileExt);
if (matcher.find()) {
//图片压缩 超200k压缩
if(fileItem.getSize()>204800){
//若图片较大需要将原文件重命名为XX-initial
File imgBig = new File(imgPath);
file.renameTo(imgBig);
imgPress(imgBig,imgPath,new StringBuffer(basePath).append(relativePath).append(uuid)
.append(fileExt).toString());
}
}
图片压缩策略:考虑本次目标是手机上传图片,一般都是尺寸像素比较大,因此采用缩小像素的方式,图片保持等比例,横竖版照片不超过480*270(这里想要压的更小可以将目标尺寸调的更小),不做放大处理。
private void imgPress(File file,String sourcePath,String targetPath) throws Exception{
FileInputStream inStream = new FileInputStream(file);
BufferedImage sourceImg =ImageIO.read(inStream);
int imgWidth=sourceImg.getWidth();
int imgHeight=sourceImg.getHeight();
double scaleW,scaleH;
if(imgWidth>imgHeight){
//横版图片
scaleW=((double)imgWidth)/((double)480);
scaleH=((double)imgHeight)/((double)270);
}else{
//竖版图片
scaleW=((double)imgWidth)/((double)270);
scaleH=((double)imgHeight)/((double)480);
}
double rate = scaleW > scaleH ? scaleW : scaleH;
int scaleActualW,scaleActualH;
// 最小比率为1
if (rate <= 1){
rate = 1;
}
scaleActualW = (int) (((double)imgWidth)/rate);
scaleActualH = (int) (((double)imgHeight)/rate);
Thumbnails.of(sourcePath).size(scaleActualW,scaleActualH).keepAspectRatio(false).toFile(targetPath);
}
图片压完还是小了不少,也没压特别厉害,后续优化待补充吧