springboot集成Thumbnailator压缩图片

一、参考大神博客

1、https://blog.51cto.com/u_11269274/5118649

2、https://blog.csdn.net/weixin_44722978/article/details/111166154

二、引用

1
2
3
4
5
6
<!-- 图片缩略图 -->
        <dependency>
            <groupId>net.coobird</groupId>
            <artifactId>thumbnailator</artifactId>
            <version>0.4.8</version>
        </dependency>

  三、上传接口中调用

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
31
32
33
34
35
36
//上传图片-压缩
  @PostMapping("/uploadPicCompress")
  @ResponseBody
  public AjaxResult uploadPicCompress(@RequestParam("file") MultipartFile file) throws IOException {
      String filePath = getProfile() + "/group";// 上传图片路径
      String fileName = file.getOriginalFilename();
      String filePath1 = FileUploadUtils.upload(filePath, file);//文件上传返回存储路径
      //压缩图片
      String filePathObj=filePath1.replaceAll("/profile", getProfile());//绝对路径
      int nameIndex=filePathObj.lastIndexOf('/');
      String pathHeader=filePathObj.substring(0,nameIndex+1);
      //图片缩放成宽度720px或者高度1100px的图片
      BufferedImage image = ImageIO.read(new File(filePathObj));
      int pictWidth = image.getWidth();
      int pictHeight = image.getHeight();
      double scaleK=1.0;//压缩比例
      if(pictWidth>720){
          scaleK=(double) 720 / pictWidth;
      }else if(pictHeight>1100){
          scaleK=(double) 1100 / pictHeight;
      }
      if(scaleK!=1.0){
          int fileNampPoint=fileName.lastIndexOf('.');
          String fileNameHead=fileName.substring(0,fileNampPoint);
          String fileNameEnd=fileName.substring(fileNampPoint);
          String scalePath=pathHeader+fileNameHead+"_"+ DateUtils.dateTimeNow()+fileNameEnd;//文件名称加时间,防止重复
          Thumbnails.of(filePathObj).scale(scaleK).toFile(scalePath);//按比例缩小
          //判断新文件保存是否成功,成功则删除原文件
          File fileNew = new File(scalePath);
          if(fileNew!=null){
              new File(filePathObj).delete();
              filePath1=scalePath.replaceAll(getProfile(),"/profile" );
          }
      }
      return AjaxResult.success(filePath1);
  }

  

posted on   七七2020  阅读(614)  评论(0编辑  收藏  举报

相关博文:
阅读排行:
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 单元测试从入门到精通
· 上周热点回顾(3.3-3.9)
· winform 绘制太阳,地球,月球 运作规律
< 2025年3月 >
23 24 25 26 27 28 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 31 1 2 3 4 5

导航

统计

点击右上角即可分享
微信分享提示