首先是添加maven依赖
<dependency>
<groupId>net.coobird</groupId>
<artifactId>thumbnailator</artifactId>
<version>0.4.8</version>
</dependency>
原图
图片压缩代码
Thumbnails.of("d:/5M.jpg").scale(1f).outputQuality(0.25f).toFile("d:/5M_s.jpg");
根据原图比例,把5M的图片缩小成了476K
另外还有其它的方法
//此处把图片压成400×500的缩略图
Thumbnails.of(fromPic).size(400,500).toFile(toPic);
//按比例缩小1/5
Thumbnails.of(fromPic).scale(0.2f).toFile(toPic);
//按比例放大2倍
Thumbnails.of(fromPic).scale(2f).toFile(toPic);
//旋转图片,rotate(角度),正数则为顺时针,负数则为逆时针
Thumbnails.of(fromPic).size(200,200).rotate(90).toFile(toPic);
//给图片加水印,watermark(位置,水印图,透明度)Positions.CENTER表示加在中间
Thumbnails.of(fromPic).size(400,400)
.watermark(Positions.CENTER,ImageIO.read(waterPic),0.5f)
.outputQuality(0.8f).toFile(toPic);