Thumbnailator是一款强大且方便的开源工具类,有很多对文件处理的api,如缩略图,图片旋转,水印等等,github地址是https://github.com/coobird/thumbnailator
引入依赖:
<dependency>
<groupId>net.coobird</groupId>
<artifactId>thumbnailator</artifactId>
<version>[0.4, 0.5)</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-mock</artifactId>
<version>2.0.8</version>
</dependency>
本次我使用到的场景就是要将上传的文件先以图片中心短边截图为正方形的图片,然后将剪切的图片压缩为宽高128*128的缩略图,代码如下:
BufferedImage bufferedImage = ImageIO.read(abbreviateInputStream);
int width = Math.min(bufferedImage.getWidth(), bufferedImage.getHeight());
byte[] fileBytes = file.getBytes();
//图片中心点以宽度为准截取正方形再按照128x128缩放
Thumbnails.of(new ByteArrayInputStream(fileBytes))
.sourceRegion(Positions.CENTER, width, width)
.size(128, 128)
.keepAspectRatio(false)
.toOutputStream(abbreviateByteArrayOutputStream);
byte[] abbreviateByteArray = abbreviateByteArrayOutputStream.toByteArray();
ByteArrayInputStream abbreviateByteArrayInputStream = new ByteArrayInputStream(abbreviateByteArray);
//字节数组转为MultipartFile
MultipartFile abbreviateImage = new MockMultipartFile(file.getName(), file.getOriginalFilename(), file.getContentType(), abbreviateByteArray);
代码里面为什么用字节数组而不直接传入InputStream流进去呢,因为直接传入InputStream会报错:大概意思就是找不到合适的图片阅读器,所以才传入ByteArrayInputStream(fileBytes)