上網找了好多關於圖片壓縮的帖子,基本上都是介紹谷歌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);
}
圖片壓完還是小了不少,也沒壓特別厲害,後續優化待補充吧