Thumbnails 壓縮後反而變大

遇到的問題:
1.Thumbnails.scale效果會導致圖片大小變大
  scale值
原圖片格式 2 1 0.8 0.6 0.4 0.2
jpeg 明顯變大 變大 變大 變大 明顯變小 變大
png 變大 變小 變小 變小 變小 最小
png經過壓縮 明顯變大 不變 變小 變小 變小 最小
png未經過壓縮 明顯變大 明顯變大 變大 變大 變小 變小
jpeg改爲png 明顯變大 明顯變大 變大 變大 變大 變小
pngtopng 明顯變大 明顯變大 明顯變大 明顯變大 明顯變大 變小

Thumbnails應該是存在bug,但是也一直沒有更新版本,所以根據多次測試得來的結果:用jpg轉成jpg效果最佳。所以當圖片爲png時,先改成jpg格式,再進行壓縮。

 

public static String imgConvert(String tempDirPath, String fileName, String fileExt) throws IOException {
    	String srcPath = tempDirPath + fileName;  //原始圖片路徑
    	if("png".equals(fileExt)) {
    		
    		//生成新圖片名稱
    		SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
            String fileString = df.format(new Date()) + "_" + new Random().nextInt(1000) + ".jpg";
            
            //新圖片全路徑
            String newJpg = tempDirPath + fileString; 
            
        	// 1、先轉換成jpg  
            Thumbnails.of(srcPath).scale(1f).toFile(newJpg); 
            
            //2.jpg圖片壓縮
            Thumbnails.of(newJpg).scale(1f).outputQuality(0.25d).toFile(newJpg);
            
            //壓縮成功後,刪除png圖片
            File f = new File(srcPath);
            f.delete();
            
            return fileString;
    	} else {
    		Thumbnails.of(srcPath).scale(1f).outputQuality(0.25d).toFile(srcPath);
    	}
    	return null;
    }

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章