1. 程式人生 > 程式設計 >Java 實現圖片壓縮的兩種方法

Java 實現圖片壓縮的兩種方法

問題背景。

典型的情景:Nemo社群中,使用者上傳的圖片免不了要在某處給使用者做展示。

如使用者上傳的頭像,那麼其他使用者在瀏覽該使用者資訊的時候,就會需要回顯頭像資訊了。

使用者上傳的原圖可能由於清晰度較高而體積也相對較大,考慮使用者流量頻寬,一般而言我們都不會直接體積巨大的原圖直接丟給使用者讓使用者慢慢下載。

這時候通常我們會在伺服器對圖片進行壓縮,然後把壓縮後的圖片內容回顯給使用者。

壓縮方案:

這裡主要找了兩個java中常用的圖片壓縮工具庫:Graphics和Thumbnailator。

1、Graphics:

    /**
	 * compressImage
	 * 
	 * @param imageByte
	 *      Image source array
	 * @param ppi
	 * @return
	 */
	public static byte[] compressImage(byte[] imageByte,int ppi) {
		byte[] smallImage = null;
		int width = 0,height = 0;
 
		if (imageByte == null)
			return null;
 
		ByteArrayInputStream byteInput = new ByteArrayInputStream(imageByte);
		try {
			Image image = ImageIO.read(byteInput);
			int w = image.getWidth(null);
			int h = image.getHeight(null);
			// adjust weight and height to avoid image distortion
			double scale = 0;
			scale = Math.min((float) ppi / w,(float) ppi / h);
			width = (int) (w * scale);
			width -= width % 4;
			height = (int) (h * scale);
 
			if (scale >= (double) 1)
				return imageByte;
 
			BufferedImage buffImg = new BufferedImage(width,height,BufferedImage.TYPE_INT_RGB);
			buffImg.getGraphics().drawImage(image.getScaledInstance(width,Image.SCALE_SMOOTH),null);
			ByteArrayOutputStream out = new ByteArrayOutputStream();
			ImageIO.write(buffImg,"png",out);
			smallImage = out.toByteArray();
			return smallImage;
 
		} catch (IOException e) {
			log.error(e.getMessage());
			throw new RSServerInternalException("");
		}
	}

重點在於:

BufferedImage buffImg = new BufferedImage(width,BufferedImage.TYPE_INT_RGB);
buffImg.getGraphics().drawImage(image.getScaledInstance(width,null);

2、Thumbnailator:

    /**
	 * compressImage
	 * 
	 * @param path
	 * @param ppi
	 * @return
	 */
	public static byte[] compressImage(String path,int ppi) {
		byte[] smallImage = null;
 
	  try {
	    ByteArrayOutputStream out = new ByteArrayOutputStream();
		Thumbnails.of(path).size(ppi,ppi).outputFormat("png").toOutputStream(out);
		smallImage = out.toByteArray();
		return smallImage;
	  } catch (IOException e) {
		log.error(e.getMessage());
		throw new RSServerInternalException("");
	  }
	}

實際測試中,批量的情境下,後者較前者更快一些。

以上就是Java 實現圖片壓縮的兩種方法的詳細內容,更多關於Java 圖片壓縮的資料請關注我們其它相關文章!