public GrayModel(ColorModel sourceModel) { super(sourceModel.getPixelSize()); this.sourceModel=sourceModel; modelStyle=0; } public GrayModel(ColorModel sourceModel,int style) { super(sourceModel.getPixelSize()); this.sourceModel=sourceModel; modelStyle=style; } public void setGrayStyle(int style) { modelStyle=style; } protected int getGrayLevel(int pixel) { if (modelStyle==CS_MAX) { return Math.max(sourceModel.getRed(pixel),Math.max(sourceModel.getGreen(pixel),sourceModel.getBlue(pixel))); } else if (modelStyle==CS_FLOAT){ return (int)(sourceModel.getRed(pixel)*0.3+sourceModel.getGreen(pixel)*0.59+sourceModel.getBlue(pixel)*0.11); } else { return 0; } } public int getAlpha(int pixel) { return sourceModel.getAlpha(pixel); } public int getRed(int pixel) { return getGrayLevel(pixel); } public int getGreen(int pixel) { return getGrayLevel(pixel); } public int getBlue(int pixel) { return getGrayLevel(pixel); } public int getRGB(int pixel) { int gray=getGrayLevel(pixel); return (getAlpha(pixel)<<24)+(gray<<16)+(gray<<8)+gray; } } 如果你有自己的算法或者想取得特殊的效果,你可以修改类GrayModel的方法getGrayLevel()。
色彩变换
根据上面的原理,我们也可以实现色彩变换,这样的效果就很多了。下面是一个反转变换的例子:
/* ReverseColorModel.java*/ /*@author:cherami */ /*email:cherami@163.net*/ import java.awt.image.*;
public class ReverseColorModel extends ColorModel { ColorModel sourceModel; public ReverseColorModel(ColorModel sourceModel) { super(sourceModel.getPixelSize()); this.sourceModel=sourceModel; } public int getAlpha(int pixel) { return sourceModel.getAlpha(pixel); } public int getRed(int pixel) { return ~sourceModel.getRed(pixel); } public int getGreen(int pixel) { return ~sourceModel.getGreen(pixel); } public int getBlue(int pixel) { return ~sourceModel.getBlue(pixel); } public int getRGB(int pixel) { return (getAlpha(pixel)<<24)+(getRed(pixel)<<16)+(getGreen(pixel)<<8)+getBlue(pixel); } } /* ReverseColorModel.java*/ /*@author:cherami */ /*email:cherami@163.net*/
import java.awt.image.*;
public class ReverseFilter extends RGBImageFilter { public ReverseFilter() { canFilterIndexColorModel=true; } public void setColorModel(ColorModel cm) { substituteColorModel(cm,new ReverseColorModel(cm)); }
|