本文中代码来自: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 stream73 JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);74 75 JPEGEncodeParam param = encoder76 .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%