java image filters[02]-过滤器初探
图片缩放应用比较多,我们看看imageFilters提供的ScaleFilter怎么完成这项工作。
首先了解怎么调用过滤器,实例代码如下:
public void imageScale(String fromPath, String toPath, int width, int height) throws IOException { // 定义“缩放过滤器” ScaleFilter scaleFilter = new ScaleFilter(width, height); BufferedImage fromImage = ImageIO.read( new File(fromPath)); // BufferedImage toImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); // 缩放处理 scaleFilter.filter(fromImage, toImage); // 写回指定目标文件 ImageIO.write(toImage, "jpg" , new File(toPath)); } |
效果如下所示:
原图:
处理后:
这里没有做等比例缩放,要想实现这个功能——在图片长宽做相应处理即可!
--------------------------------------
来了解下ScaleFilter内部怎么处理的!
public BufferedImage filter( BufferedImage src, BufferedImage dst ) { if ( dst == null ) { ColorModel dstCM = src.getColorModel(); dst = new BufferedImage(dstCM, dstCM.createCompatibleWritableRaster( width, height ), dstCM.isAlphaPremultiplied(), null ); } Image scaleImage = src.getScaledInstance( width, height, Image.SCALE_AREA_AVERAGING ); Graphics2D g = dst.createGraphics(); g.drawImage( scaleImage, 0 , 0 , width, height, null ); g.dispose(); return dst; } |
关键类:
- BufferedImage
- Image
- Graphics2D
-----------------------------------------------
图片黑白处理(去颜色)
public void gray(String fromPath, String toPath) throws IOException { // 定义过滤器 GrayscaleFilter filter = new GrayscaleFilter(); BufferedImage fromImage = ImageIO.read( new File(fromPath)); int width = fromImage.getWidth(); int height = fromImage.getHeight(); BufferedImage toImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); // for ( int i = 0 ; i < width; i++) { for ( int j = 0 ; j < height; j++) { int rgb = fromImage.getRGB(i, j); // 过滤 int grayValue = filter.filterRGB(i, j, rgb); toImage.setRGB(i, j, grayValue); } } // ImageIO.write(toImage, "jpg" , new File(toPath)); } |
效果:
内部实现原理:
public int filterRGB( int x, int y, int rgb) { int a = rgb & 0xff000000 ; int r = (rgb >> 16 ) & 0xff ; int g = (rgb >> 8 ) & 0xff ; int b = rgb & 0xff ; // rgb = (r + g + b) / 3; // simple average rgb = (r * 77 + g * 151 + b * 28 ) >> 8 ; // NTSC luma return a | (rgb << 16 ) | (rgb << 8 ) | rgb; } |
注意点:还有一个过滤器是GrayFilter,注意和这里的GrayscaleFilter予以区别。