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;
        }
    }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM