Thumbnailator,一个google开源的优秀的工具类 。根据提供的API可以快速实现图片缩放,区域裁剪,水印,旋转,保持比例 等操作。
Thumbnailator官网:http://code.google.com/p/thumbnailator/
本文主要讲图片原比例压缩功能。
1、引入maven依赖
2、demo测试
public class TestImageUtil { public static void main(String[] args) throws IOException { String originImgPath = "C:UsersHoscenDesktopit.png"; String destImgPath = "C:UsersHoscenDesktopit-30.jpg"; Thumbnails.of(originImgPath) .scale(1f) .outputQuality(0.3f) .outputFormat("jpg") .toFile(destImgPath); } }
3、测试结果
原图,大小82.5kb
压缩后, 大小30.1kb
4、总结
scale是可以指定图片的大小,值在0到1之间,1f就是原图大小,0.5就是原图的一半大小,这里的大小是指图片的长宽;
outputQuality是图片的质量,值也是在0到1,越接近于1质量越好,越接近于0质量越差;
经测试发现png格式图片压缩有问题,建议统一将图片压缩后的格式设置成jpg格式.outputFormat("jpg")