1. 程式人生 > >java圖片高保真縮放

java圖片高保真縮放

public class NarrowImage {

	/**
	 * @param im
	 *            原始影象
	 * @param resizeTimes
	 *            倍數,比如0.5就是縮小一半,0.98等等double型別
	 * @return 返回處理後的影象
	 */
	public BufferedImage zoomImage(String src) {
		
		BufferedImage result = null;

		try {
			File srcfile = new File(src);
			if (!srcfile.exists()) {
				System.out.println("檔案不存在");
				
			}
			BufferedImage im = ImageIO.read(srcfile);

			/* 原始影象的寬度和高度 */
			int width = im.getWidth();
			int height = im.getHeight();
			
			//壓縮計算
			float resizeTimes = 0.3f;  /*這個引數是要轉化成的倍數,如果是1就是轉化成1倍*/
			
			/* 調整後的圖片的寬度和高度 */
			int toWidth = (int) (width * resizeTimes);
			int toHeight = (int) (height * resizeTimes);

			/* 新生成結果圖片 */
			result = new BufferedImage(toWidth, toHeight,
					BufferedImage.TYPE_INT_RGB);

			result.getGraphics().drawImage(
					im.getScaledInstance(toWidth, toHeight,
							java.awt.Image.SCALE_SMOOTH), 0, 0, null);
			

		} catch (Exception e) {
			System.out.println("建立縮圖發生異常" + e.getMessage());
		}
		
		return result;

	}
	
	 public boolean writeHighQuality(BufferedImage im, String fileFullPath) {
	        try {
	            /*輸出到檔案流*/
	            FileOutputStream newimage = new FileOutputStream(fileFullPath);
	            JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(newimage);
	            JPEGEncodeParam jep = JPEGCodec.getDefaultJPEGEncodeParam(im);
	            /* 壓縮質量 */
	            jep.setQuality(0.9f, true);
	            encoder.encode(im, jep);
	           /*近JPEG編碼*/
	            newimage.close();
	            return true;
	        } catch (Exception e) {
	            return false;
	        }
	    }
	 
	 
	 public static void main(String[] args) {
		 
		 String inputFoler = "E:\\新建資料夾\\7.jpg" ; 
         /*這兒填寫你存放要縮小圖片的資料夾全地址*/
        String outputFolder = "E:\\新建資料夾\\07.jpg";  
        /*這兒填寫你轉化後的圖片存放的資料夾*/
      
       
		 
		 NarrowImage narrowImage = new NarrowImage();
		 narrowImage.writeHighQuality(narrowImage.zoomImage(inputFoler), outputFolder);
		
	}

}