springboot集成Thumbnailator压缩图片

一、参考大神博客

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

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

二、引用

<!-- 图片缩略图 -->
        <dependency>
            <groupId>net.coobird</groupId>
            <artifactId>thumbnailator</artifactId>
            <version>0.4.8</version>
        </dependency>

  三、上传接口中调用

  //上传图片-压缩
    @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 2022-07-01 09:45  七七2020  阅读(582)  评论(0编辑  收藏  举报

导航