Thumbnails图片压缩处理工具

本文介绍如何使用Thumbnails工具进行图片的压缩处理,包括按大小或比例缩放、旋转等功能,并提供了一个SpringMVC框架中处理上传图片的具体示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Thumbnails是google公司开源的图片压缩、处理的工具,可以对图片按大小或比例缩放、旋转、加水印、裁剪等。

1、pom.xml引入


  <!--图片压缩工具-->
    <dependency>
      <groupId>net.coobird</groupId>
      <artifactId>thumbnailator</artifactId>
      <version>0.4.12</version>
    </dependency>

2、springMVC上传文件压缩处理(示例代码)

@RequestMapping(value = "/upload",method = RequestMethod.POST)
public RetMsg upload(@RequestParam(value = "file",required = false)
                              MultipartFile file) throws Exception{
   if(file==null || file.getSize()==0){
       return RetMsg.failure("上传文件不能为空");
   }
   String orgFileName = file.getOriginalFilename();
   String contentType =file.getContentType();//文件的contentType
 
   byte[] bytes=null;//字节数据
   
   if(file.getSize()>=1024*1024*10){ //10M
        return RetMsg.failure("上传文件太大,不得超过10M");
   }
   if(file.getSize()>4*1024*1024){//4M  如果图片大于4M进行压缩处理
       InputStream in=file.getInputStream();
       ByteArrayOutputStream out =new ByteArrayOutputStream(1024*1024);
       Thumbnails.of(in).scale(0.5,0.5).outputQuality(1.0).toOutputStream(out);//将图片进行压缩 0.5*0.5
       bytes=out.toByteArray();
   }else{
       bytes=file.getBytes();
   }
 
uploadService.uploadFile(bytes);
    return RetMsg.success() ;
 
}

 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值