java后台图片处理Thumbnails

1.maven引入
<dependency>
   <groupId>net.coobird</groupId>
   <artifactId>thumbnailator</artifactId>
   <version>0.4.8</version>
</dependency>

或者导入jar
import net.coobird.thumbnailator.Thumbnails;

二、用法:
1.按指定大小把图片进行缩和放(会遵循原图高宽比例)
//此处把图片压成400×500的缩略图
Thumbnails.of(fromPic).size(400,500).toFile(toPic);//变为400*500
//按照比例进行缩小和放大
Thumbnails.of(fromPic).scale(0.2f).toFile(toPic);//按比例缩小
Thumbnails.of(fromPic).scale(2f);//按比例放大
//不按比例,就按指定的大小进行缩放
Thumbnails.of(fromPic).size(100, 100).keepAspectRatio(false).toFile(toPic);
或者Thumbnails.of(fromPic).forceSize(100,100).toFile(toPic);

2.旋转图片
rotate(角度),正数则为顺时针,负数则为逆时针
Thumbnails.of(fromPic).size(200,200).rotate(90).toFile(toPic);

3.图片尺寸不变,压缩图片文件大小outputQuality实现,参数1为最高质量
Thumbnails.of(fromPic).scale(1f).outputQuality(0.25f).toFile(toPic);

4.给图片加水印,watermark(位置,水印图,透明度)Positions.CENTER表示加在中间
Thumbnails.of(fromPic).size(400,400)
        .watermark(Positions.CENTER,ImageIO.read(waterPic),0.5f)
        .outputQuality(0.8f).toFile(toPic);

5.用sourceRegion()实现图片裁剪
//图片中心300*300的区域,Positions.CENTER表示中心,还有许多其他位置可选
Thumbnails.of(fromPic).sourceRegion(Positions.CENTER,300,300)
        .size(300,300).toFile(toPic);
//图片中上区域300*300的区域
Thumbnails.of(fromPic).sourceRegion(Positions.TOP_CENTER,300,300)
        .size(300,300).toFile(toPic);
Thumbnails.of(fromPic).sourceRegion(0,0,200,200)
        .size(300,300).toFile(toPic);

 

posted @ 2021-01-22 17:55  景、  阅读(452)  评论(0编辑  收藏  举报