使用Thumbnails實現圖片指定大小壓縮

項目中有個要求,對上傳服務器的圖片大小進行判斷,大於500k的圖片要進行壓縮處理,讓其小於500k後在上傳。

可以通過java api的ImageIO實現圖片壓縮,但是看了網上的博客普遍都說bug比較多,會有OOM內存溢出的現象。

Thumbnails插件是Google的插件,能指定不同的參數進行壓縮操作。
比如:寬高(size),縮放(scale),制定質量比(outputQuality)等。

插件使用的jar包爲:
thumbnailator-0.4.8.jar

代碼如下:

	/**
	 * 
	 * @param srcPath  原圖片地址
	 * @param desPath  目標圖片地址
	 * @param desFileSize  指定圖片大小,單位kb
	 * @param accuracy 精度,遞歸壓縮的比率,建議小於0.9
	 * @return
	 */
	public static String commpressPicForScale(String srcPath,String desPath,
			long desFileSize , double accuracy){
		try {
			File srcFile  = new File(srcPath);
			long srcFilesize = srcFile.length();
			System.out.println("原圖片:"+srcPath + ",大小:" + srcFilesize/1024 + "kb");
			//遞歸壓縮,直到目標文件大小小於desFileSize
			commpressPicCycle(desPath, desFileSize, accuracy);
			
			File desFile = new File(desPath);
			System.out.println("目標圖片:" + desPath + ",大小" + desFile.length()/1024 + "kb");
			System.out.println("圖片壓縮完成!");
		} catch (Exception e) {
			e.printStackTrace();
		}
		return desPath;
	}

	public static void commpressPicCycle(String desPath , long desFileSize,
			double accuracy) throws IOException{
		File imgFile = new File(desPath);
		long fileSize  = imgFile.length();
		//判斷大小,如果小於500k,不壓縮,如果大於等於500k,壓縮
		if(fileSize <= desFileSize * 500){
			return;
		}
		//計算寬高
		BufferedImage  bim = ImageIO.read(imgFile);
		int imgWidth = bim.getWidth();
		int imgHeight = bim.getHeight();
		int desWidth = new BigDecimal(imgWidth).multiply(
                new BigDecimal(accuracy)).intValue();
        int desHeight = new BigDecimal(imgHeight).multiply(
                new BigDecimal(accuracy)).intValue();
        Thumbnails.of(desPath).size(desWidth, desHeight).outputQuality(accuracy).toFile(desPath);
        //如果不滿足要求,遞歸直至滿足小於1M的要求
        commpressPicCycle(desPath, desFileSize, accuracy);
	}

然後壓縮圖片大小:

commpressPicForScale(filePath, filePath, 500, 0.8);

壓縮完成:
在這裏插入圖片描述

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