1. 程式人生 > >一個java圖片縮放及質量壓縮方法

一個java圖片縮放及質量壓縮方法

exceptio nco dep example codes 圖片 round 調用 java

由於網站需要對上傳的圖片進行寬度判斷縮放和質量壓縮,以提升整體加載速度,於是我在網上找處理方法,
網上大多數是谷歌圖片處理組件Thumbnails的介紹。最開始我用Thumbnails嘗試,但不知道什麽原因,沒有任何效果,也不報錯。
由於時間的關系,就沒再深入研究,另尋他路。後來找到了下面的方法,這個方法優點在於完全基於Java自帶API,調用也非常簡單,如果只是縮放和壓縮,這個方法足夠了。
代碼:
 1     /**
 2      * 縮放圖片(壓縮圖片質量,改變圖片尺寸)
 3      * 若原圖寬度小於新寬度,則寬度不變!
 4      * @param newWidth 新的寬度
 5
* @param quality 圖片質量參數 0.7f 相當於70%質量 6 */ 7 public static void imageResize(File originalFile, File resizedFile, 8 int newWidth, float quality) throws IOException { 9 10 if (quality > 1) { 11 throw new IllegalArgumentException( 12 "圖片質量需設置在0.1-1範圍");
13 } 14 15 ImageIcon ii = new ImageIcon(originalFile.getCanonicalPath()); 16 Image i = ii.getImage(); 17 Image resizedImage = null; 18 19 int iWidth = i.getWidth(null); 20 int iHeight = i.getHeight(null); 21 22 if(iWidth < newWidth){ 23 newWidth = iWidth;
24 } 25 if (iWidth > iHeight) { 26 resizedImage = i.getScaledInstance(newWidth, (newWidth * iHeight) 27 / iWidth, Image.SCALE_SMOOTH); 28 } else { 29 resizedImage = i.getScaledInstance((newWidth * iWidth) / iHeight, 30 newWidth, Image.SCALE_SMOOTH); 31 } 32 33 // This code ensures that all the pixels in the image are loaded. 34 Image temp = new ImageIcon(resizedImage).getImage(); 35 36 // Create the buffered image. 37 BufferedImage bufferedImage = new BufferedImage(temp.getWidth(null), 38 temp.getHeight(null), BufferedImage.TYPE_INT_RGB); 39 40 // Copy image to buffered image. 41 Graphics g = bufferedImage.createGraphics(); 42 43 // Clear background and paint the image. 44 g.setColor(Color.white); 45 g.fillRect(0, 0, temp.getWidth(null), temp.getHeight(null)); 46 g.drawImage(temp, 0, 0, null); 47 g.dispose(); 48 49 // Soften. 50 float softenFactor = 0.05f; 51 float[] softenArray = { 0, softenFactor, 0, softenFactor, 52 1 - (softenFactor * 4), softenFactor, 0, softenFactor, 0 }; 53 Kernel kernel = new Kernel(3, 3, softenArray); 54 ConvolveOp cOp = new ConvolveOp(kernel, ConvolveOp.EDGE_NO_OP, null); 55 bufferedImage = cOp.filter(bufferedImage, null); 56 57 // Write the jpeg to a file. 58 FileOutputStream out = new FileOutputStream(resizedFile); 59 60 // Encodes image as a JPEG data stream 61 JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out); 62 63 JPEGEncodeParam param = encoder 64 .getDefaultJPEGEncodeParam(bufferedImage); 65 66 param.setQuality(quality, true); 67 68 encoder.setJPEGEncodeParam(param); 69 encoder.encode(bufferedImage); 70 } // Example usage

調用:

1 //圖片壓縮處理(縮放+質量壓縮以減小高寬度及數據量大小)
2             imageResize(imgFile,imgFile,1200,0.7f);//寬度大於1200的,縮放為1200,質量壓縮掉30%,一張接近200k的圖片壓縮後大約為90多k

一個java圖片縮放及質量壓縮方法