先了解一下png,jpg是什么;
png:png(便携式网络图形)是一种无损压缩的位图片形格式
jpg,jpge 是有损压缩的图片形式,会产生迭代有损,在重复压缩和解码的过程中会不断丢失信息使图像质量下降。
使用Thumbnails压缩图片的话,
输出png格式图片建议调整scale的值压缩图片分辨率,
输出jpg 图片建议调整outputFormat的值压缩图片质量
下面进行一个简单测试:
找一个测试图片,下图大小为7.41MB
Maven引入压缩jar包
<dependency>
<groupId>net.coobird</groupId>
<artifactId>thumbnailator</artifactId>
<version>0.4.8</version>
</dependency>
public static void main(String[] args) {
File file = new File("C:/Users/Administrator/Desktop/test/test.jpg");
try {
BigDecimal bigDecimal = new BigDecimal("1");
for (int i = 0; i <= 9; i++) {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
Thumbnails.of(file).scale(1f).outputFormat("jpg")
.outputQuality(bigDecimal.doubleValue()).toOutputStream(baos);
byte[] byteArray = baos.toByteArray();
OutputStream os = new FileOutputStream("C:/Users/Administrator/Desktop/test/test"+ bigDecimal +".jpg");
os.write(byteArray, 0, byteArray.length);
os.flush();
os.close();
bigDecimal = bigDecimal.subtract(new BigDecimal("0.1"));
}
} catch (IOException e) {
e.printStackTrace();
}
}
执行以后,生成以下图片:
随着outputQuality的值减小,生成的图片也越来越小
但是我们查看test0.1.jpg的属性,只是大小改变,分辨率并未改变
追求质量大小的话,建议输出jpg格式图片,
优点:压缩最小且清晰
缺点:图片色彩易淡化