标签:paint getc loaded 尺寸 div put buffer 开始 hit
由于网站需要对上传的图片进行宽度判断缩放和质量压缩,以提升整体加载速度,于是我在网上找处理方法,
网上大多数是谷歌图片处理组件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
标签:paint getc loaded 尺寸 div put buffer 开始 hit
原文地址:http://www.cnblogs.com/jsper/p/7652896.html