Java使用 Thumbnails 压缩图片

业务:用户上传一张图片到文件站,需要返回原图url和缩略图url

处理思路:

  1. 因为上传图片方法返回url是单个上传,第一步先上传原图并返回url
  2. 处理缩略图并上传:拿到MultipartFile压缩成缩略图后存放到项目内指定文件夹
  3. 用项目内新生成的缩略图转换为MultipartFile发送给图片上传方法得到url
  4. 流程处理完后删除存放在项目内的缩略图
    public void imageMethod(MultipartFile file){
 
        //region/-------创建缩略图存放的文件夹-------/
        //获得项目根目录
        String path = System.getProperty("user.dir");
        //定义新文件夹路径
        String dirPath = path + File.separator + "imagecache";
        //根据路径生成文件夹
        File dir = new File(dirPath);
        dir.mkdirs();
        //endregion
 
        //定义缩略图的全路径
        String fileSuffix = "image.jpg";
        String contextPath = dirPath + File.separator + fileSuffix;
 
        //压缩图片
        MultipartFile newFile = null;
        try {
            //自定义宽高压缩(压缩方法很多,可以根据需求更改)
            Thumbnails.of(file.getInputStream()).forceSize(100, 100).toFile(contextPath);
 
            //压缩完成后将缩略图生成MultipartFile
            FileItem fileItem = createFileItem(contextPath);
            newFile = new CommonsMultipartFile(fileItem);
 
        } catch (IOException e) {
            e.printStackTrace();
        }
        //endregion
 
        //上面的“newFile”就是缩略图转换后的MultipartFile,就可以拿来用了
 
        //程序处理完后把生成的缩略图删除
        File image = new File(contextPath);
        if (image.exists()) {
            image.delete();
        }
 
    }
 
 
 
    /**
     * 获取压缩后的图片,File 转为 MultipartFile
     *
     */
    public FileItem createFileItem(String contextPath) {
        {
            FileItemFactory factory = new DiskFileItemFactory(16, null);
            String textFieldName = "textField";
            int num = contextPath.lastIndexOf(".");
            String extFile = contextPath.substring(num);
            FileItem item = factory.createItem(textFieldName, "text/plain", true,
                    "MyFileName" + extFile);
            File newfile = new File(contextPath);
            int bytesRead = 0;
            byte[] buffer = new byte[8192];
            try {
                FileInputStream fis = new FileInputStream(newfile);
                OutputStream os = item.getOutputStream();
                while ((bytesRead = fis.read(buffer, 0, 8192))
                        != -1) {
                    os.write(buffer, 0, bytesRead);
                }
                os.close();
                fis.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            return item;
        }
    }
原文地址:https://www.cnblogs.com/seanvigour/p/13045140.html