使用Thumbnailator工具类生成缩略图

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)

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值