本文中代碼來自:http://blog.csdn.net/liuhuanchao/article/details/50527856
由於網站需要對上傳的圖片進行寬度判斷縮放和質量壓縮,以提升整體加載速度,於是我在網上找處理方法,
網上大多數是谷歌圖片處理組件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 maxWidth,int maxHeight, 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 int newWidth = maxWidth; 23 if(iWidth < maxWidth){ 24 newWidth = iWidth; 25 } 26 27 28 if (iWidth >= iHeight) { 29 resizedImage = i.getScaledInstance(newWidth, (newWidth * iHeight) 30 / iWidth, Image.SCALE_SMOOTH); 31 } 32 33 34 35 int newHeight = maxHeight; 36 if(iHeight < maxHeight){ 37 newHeight = iHeight; 38 } 39 40 if(resizedImage==null && iHeight >= iWidth){ 41 resizedImage = i.getScaledInstance((newHeight * iWidth) / iHeight, 42 newHeight, Image.SCALE_SMOOTH); 43 } 44 45 // This code ensures that all the pixels in the image are loaded. 46 Image temp = new ImageIcon(resizedImage).getImage(); 47 48 // Create the buffered image. 49 BufferedImage bufferedImage = new BufferedImage(temp.getWidth(null), 50 temp.getHeight(null), BufferedImage.TYPE_INT_RGB); 51 52 // Copy image to buffered image. 53 Graphics g = bufferedImage.createGraphics(); 54 55 // Clear background and paint the image. 56 g.setColor(Color.white); 57 g.fillRect(0, 0, temp.getWidth(null), temp.getHeight(null)); 58 g.drawImage(temp, 0, 0, null); 59 g.dispose(); 60 61 // Soften. 62 float softenFactor = 0.05f; 63 float[] softenArray = { 0, softenFactor, 0, softenFactor, 64 1 - (softenFactor * 4), softenFactor, 0, softenFactor, 0 }; 65 Kernel kernel = new Kernel(3, 3, softenArray); 66 ConvolveOp cOp = new ConvolveOp(kernel, ConvolveOp.EDGE_NO_OP, null); 67 bufferedImage = cOp.filter(bufferedImage, null); 68 69 // Write the jpeg to a file. 70 FileOutputStream out = new FileOutputStream(resizedFile); 71 72 // Encodes image as a JPEG data stream 73 JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out); 74 75 JPEGEncodeParam param = encoder 76 .getDefaultJPEGEncodeParam(bufferedImage); 77 78 param.setQuality(quality, true); 79 80 encoder.setJPEGEncodeParam(param); 81 encoder.encode(bufferedImage); 82 } // Example usage
調用:
1 //圖片壓縮處理(縮放+質量壓縮以減小高寬度及數據量大小) 2 imageResize(imgFile,imgFile,1200,3000,0.9f);//寬度大於1200的,縮放為1200,高度大於3000的縮放為3000,按比例縮放,質量壓縮掉10%