将图片压缩至指定大小Kb(Thumbnailator)

放代码前,先唠叨唠叨,舒缓一下我的郁闷之情。

今天下午改一个后台管理系统的需求,要求上传的图片要压缩到300kb,感觉不难,就开搞。

先撩拨一下度娘,搞点货出来瞅瞅,不复杂就干脆搬砖算了。

嗯,度娘不愧为度娘,货不少,找到一个简单(优秀)的一匹的博文,用的是一个优秀的google开源的图片处理的java类库Thumbnailator(想了解么,有大神总结了[Thumbnailator使用简介],和前面那篇差不多,呵呵)。

不过呢,他们只是介绍了这个优秀的类库的使用,而我需要指定将图片压缩到多大,所以说呢,度娘真美,要啥给啥[使用Thumbnails实现图片指定大小压缩],美滋滋,开始搬砖,搬完还要搞其他的事呢。

燃,冰卵,由于开发框架用的是闲大赋团队开发的SpringBoot-Plus的后台管理系统,他的图片上传后,会在图片名称后加上UUID,这就导致了,使用Thumbnailator中的方法输出文件时,会报net.coobird.thumbnailator.tasks.UnsupportedFormatException: No suitable ImageReader found for source data.-找不到合适的图片阅读器的异常,因为后缀不在是图片的后缀了,而是一串UUID。无奈的我,只能想办法解决咯。

幸运的是,有大佬[java图片压缩(Thumbnails)]在,我站上了巨人的肩膀,哈哈哈

好了,不逼逼了,放上代码,记录一下:

SpringBoot-Plus的图片上传方法,略作修改:
/*附件类操作*/
@PostMapping(MODEL + "/uploadAttachment.json")
@ResponseBody
public JsonResult uploadFile(@RequestParam("file") MultipartFile file,String batchFileUUID,String bizType,String bizId) throws IOException {
    if(file.isEmpty()) {
        return JsonResult.fail();
    }
    System.out.println(batchFileUUID + "========= type =========   "  + bizType + "   "  + bizId  );
    CoreUser user = platformService.getCurrentUser();
    CoreOrg  org = platformService.getCurrentOrg();
    FileItem fileItem = fileService.createFileItem(file.getOriginalFilename(), bizType, bizId, user.getId(), org.getId(), batchFileUUID,null);
    saveAttachment(file,batchFileUUID,bizId,user,fileItem);
    OutputStream os = fileItem.openOutpuStream();
    // 添加判断,上传的文件是否是图片
    if("jpg|png|gif|bmp|jpeg".contains(file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".")+1))){
        // 使用压缩方法
        byte[] bytes = FileUtil.commpressPicCycle(file.getBytes(), 300, 0.5f);
        os.write(bytes);
        os.close();
    }else {
        FileUtil.copy(file.getInputStream(), os);
    }
    return JsonResult.success(fileItem);
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
压缩方法:
/**
     *
     * @param bytes 原图片字节数组
     * @param desFileSize 指定图片大小,单位 kb
     * @param accuracy 精度,递归压缩的比率,建议小于0.9
     * @return
     */
    public static byte[] commpressPicCycle(byte[] bytes, long desFileSize, double accuracy) throws IOException{
        // 获取目标图片
//        File imgFile = new File(desPath);
//        long fileSize = imgFile.length();
        long fileSize = bytes.length;
        System.out.println("=====fileSize======== "+fileSize);
        // 判断图片大小是否小于指定图片大小
        if(fileSize <= desFileSize * 1024){
            return bytes;
        }
        //计算宽高
        BufferedImage bim = ImageIO.read(new ByteArrayInputStream(bytes));
        int imgWidth = bim.getWidth();
        System.out.println(imgWidth+"====imgWidth=====");
        int imgHeight = bim.getHeight();
        int desWidth = new BigDecimal(imgWidth).multiply( new BigDecimal(accuracy)).intValue();
        System.out.println(desWidth+"====desWidth=====");
        int desHeight = new BigDecimal(imgHeight).multiply( new BigDecimal(accuracy)).intValue();
        ByteArrayOutputStream baos = new ByteArrayOutputStream(); //字节输出流(写入到内存)
        Thumbnails.of(new ByteArrayInputStream(bytes)).size(desWidth, desHeight).outputQuality(accuracy).toOutputStream(baos);
        //如果不满足要求,递归直至满足要求
        return commpressPicCycle(baos.toByteArray(), desFileSize, accuracy);
    }
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
好了,记录完成。
————————————————
版权声明:本文为CSDN博主「IT小浣熊」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/qq_43225978/article/details/103623850

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值