package binimage.utils;import java.awt.image.BufferedImage;import java.awt.image.ColorModel;publicabstractclassAbstractImageOptionFilter{publicabstract BufferedImage process(BufferedImage image);publicstatic BufferedImage createCompatibleDestImage(BufferedImage src, ColorModel dstCM){if(dstCM == null)
dstCM = src.getColorModel();returnnewBufferedImage(dstCM, dstCM.createCompatibleWritableRaster(src.getWidth(), src.getHeight()),
dstCM.isAlphaPremultiplied(), null);}publicstaticintclamp(int value){return value <0?0:((value >255)?255: value);}/**
* A convenience method for getting ARGB pixels from an image. This tries to
* avoid the performance penalty of BufferedImage.getRGB unmanaging the
* image.
*/publicstaticint[]getRGB(BufferedImage image,int x,int y,int width,int height,int[] pixels){int type = image.getType();if(type == BufferedImage.TYPE_INT_ARGB || type == BufferedImage.TYPE_INT_RGB)return(int[]) image.getRaster().getDataElements(x, y, width, height, pixels);return image.getRGB(x, y, width, height, pixels,0, width);}/**
* A convenience method for setting ARGB pixels in an image. This tries to
* avoid the performance penalty of BufferedImage.setRGB unmanaging the
* image.
*/publicstaticvoidsetRGB(BufferedImage image,int x,int y,int width,int height,int[] pixels){int type = image.getType();if(type == BufferedImage.TYPE_INT_ARGB || type == BufferedImage.TYPE_INT_RGB)
image.getRaster().setDataElements(x, y, width, height, pixels);else
image.setRGB(x, y, width, height, pixels,0, width);}}
BinaryFilter
package binimage.binary;import binimage.utils.AbstractImageOptionFilter;import java.awt.image.BufferedImage;publicclassBinaryFilterextendsAbstractImageOptionFilter{privatestaticfinaldouble WIGHT =1.0/3.0;@Overridepublic BufferedImage process(BufferedImage image){int width = image.getWidth();int height = image.getHeight();int[] pixels =newint[width * height];getRGB(image,0,0, width, height, pixels);int r =0, g =0, b =0;int offset;for(int row =0; row < height; row++){
offset = row * width;for(int col =0; col < width; col++){
r =(pixels[offset + col]>>16)&0xff;
g =(pixels[offset + col]>>8)&0xff;
b =(pixels[offset + col])&0xff;int gray =(int)((r + g + b)* WIGHT);
pixels[offset + col]= gray;}}int sum =0;int count = pixels.length;for(int i =0; i < pixels.length; i++){
sum += pixels[i];}int means = sum / count;// 二值化for(int i =0; i < pixels.length; i++){if(pixels[i]> means){
pixels[i]=(0xff<<24)|((255&0xff)<<16)|((255&0xff)<<8)|(255&0xff);}else{// 黑色
pixels[i]=(0xff<<24)|((0&0xff)<<16)|((0&0xff)<<8)|(0&0xff);}}
BufferedImage bi =newBufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);setRGB(bi,0,0, width, height, pixels);return bi;}}