1. 程式人生 > >SpringMvc圖片壓縮上傳

SpringMvc圖片壓縮上傳

一個簡單的圖片壓縮上傳方法,支援按比例縮放或按尺寸強制縮放

/***
 * 
 * @param newFilePath 生成的檔案路徑
 * @param file SpringMvc接收到的檔案
 * @param width 儲存的圖片的寬
 * @param height 儲存的圖片的高
 * @param isRatio 是否等比例縮放,true為按比例縮放,false為按固定尺寸縮放
 * @return 帶路徑的檔名稱
 * @throws IllegalStateException
 * @throws IOException
 * @author Pcject
 */
public static String imgUploadZip(String newFilePath,MultipartFile file,int width,int height,boolean isRatio)throws IllegalStateException, IOException{
     Image img = ImageIO.read(file.getInputStream());      // 取檔案流構造Image物件  
     int widthR = img.getWidth(null);    // 得到源圖寬  
     int heightR = img.getHeight(null);  // 得到源圖寬
     int widthW =0;
     int heightW =0;
     if(isRatio)
     {
         // 按照寬度還是高度進行壓縮
          //注意幾個變數都是int型別,需要加float強轉,否則取整很容易都相等
         if (((float)widthR / heightR) > ((float)width / height)) {  
             heightW = (int) (heightR * width / widthR);  
             widthW = width;  
            } else {  
                 heightW = height;  
                 widthW = (int) (widthR* height / heightR);
            } 
     }
     else {
        heightW = height;
        widthW = width;
    }
        BufferedImage image = new BufferedImage(widthW, heightW,BufferedImage.TYPE_INT_RGB );   
        image.getGraphics().drawImage(img, 0, 0, widthW, heightW, null); // 繪製縮小後的圖  
        String result = "";
        String name = file.getOriginalFilename();
        name = name.replace(".", ",");
        String[] str = name.split(",");//獲取檔案字尾名
        String fileName = TdExpBasicFunctions.GETDATETIME() +"."+str[str.length-1];
        File file2 = new File(newFilePath);
        if (!file2.exists())
            file2.mkdirs();
        String filePath = newFilePath + fileName;
        ImageIO.write(image, str[str.length-1], new File(filePath));    
        result = newFilePath + fileName;
        return result;
}