使用第三方工具Thumbnailator动态改变图片尺寸
Thumbnailator项目git地址:https://github.com/coobird/thumbnailator
使用步骤
1.添加依赖
<!-- Thumbnailator图片处理 -->
<dependency>
<groupId>net.coobird</groupId>
<artifactId>thumbnailator</artifactId>
<version>0.4.8</version>
</dependency>
2.源图片来源有2种方式:第一种从文件中读取图片,第二种从文件流中读取图片
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
try { Thumbnails.of(new File("C:/Users/Pictures/Saved Pictures/logo1.png")) .size(500, 500) .toFile(new File("D:/data/images/thumbnai3.jpg")); } catch (IOException e) { e.printStackTrace(); }
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
try { InputStream inputStream = new FileInputStream(new File("C:/Users/Pictures/Saved Pictures/logo1.png")); Thumbnails.of(inputStream) .size(500, 500) .toFile(new File("D:/data/images/thumbnai3.jpg")); } catch (IOException e) { e.printStackTrace(); }
3.输出图片方式:输出图片文件或文件流
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
Thumbnails.of(new File("C:/Users/Pictures/Saved Pictures/logo1.png")) .size(500, 500) .toFile(new File("D:/data/images/thumbnai3.jpg"));
或者
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
InputStream inputStream = new ByteArrayInputStream(fileContent); BufferedImage afterImage = Thumbnails.of(inputStream) .size(afterSize, afterSize) //按指定大小把图片进行缩和放(会遵循原图高宽比例) // .scale(1.00f) //按照指定比例进行缩小和放大 // .rotate(90) //旋转图片,rotate(角度),正数则为顺时针,负数则为逆时针 // .outputQuality(1) //压缩图片文件大小,1为最高质量 // .watermark(Positions.CENTER,ImageIO.read(waterPic),0.5f) //给图片加水印,watermark(位置,水印图,透明度)Positions.CENTER表示加在中间 // .sourceRegion(Positions.CENTER,300,300) //用sourceRegion()实现图片裁剪,图片中心300*300的区域,Positions.CENTER表示中心 // .outputFormat("png") //用outputFormat(图像格式)转换图片格式,保持原尺寸不变 .asBufferedImage();