Java压缩图片
public static void main(String[] args) {
ArticleController.commpressPicForSize(upload,upload, 100, 0.3);
}
public static String commpressPicForSize(String srcPath, String desPath,
long desFileSize, double accuracy) {
if (StringUtils.isEmpty(srcPath) || StringUtils.isEmpty(srcPath)) {
return null;
}
if (!new File(srcPath).exists()) {
return null;
}
try {
File srcFile = new File(srcPath);
long srcFileSize = srcFile.length();
System.out.println("源图片:" + srcPath + ",大小:" + srcFileSize / 1024
+ "kb");
Thumbnails.of(srcPath).scale(1f).toFile(desPath);
commpressPicCycle(desPath, desFileSize, accuracy);
File desFile = new File(desPath);
System.out.println("目标图片:" + desPath + ",大小" + desFile.length()
/ 1024 + "kb");
System.out.println("图片压缩完成!");
} catch (Exception e) {
e.printStackTrace();
return null;
}
return desPath;
}
private static void commpressPicCycle(String desPath, long desFileSize,
double accuracy) throws IOException {
File srcFileJPG = new File(desPath);
long srcFileSizeJPG = srcFileJPG.length();
if (srcFileSizeJPG <= desFileSize * 1024) {
return;
}
BufferedImage bim = ImageIO.read(srcFileJPG);
int srcWdith = bim.getWidth();
int srcHeigth = bim.getHeight();
int desWidth = new BigDecimal(srcWdith).multiply(
new BigDecimal(accuracy)).intValue();
int desHeight = new BigDecimal(srcHeigth).multiply(
new BigDecimal(accuracy)).intValue();
Thumbnails.of(desPath).size(desWidth, desHeight)
.outputQuality(accuracy).toFile(desPath);
commpressPicCycle(desPath, desFileSize, accuracy);
}