Tuesday, November 4, 2008

GrayModel

import java.awt.image.*;

// This class implements a gray color model
// scheme based on another color model. It acts
// like a gray filter. To compute the amount of
// gray for a pixel, it takes the max of the red,
// green, and blue components and uses that value
// for all three color components.

public class GrayModel extends ColorModel
{
ColorModel originalModel;

public GrayModel(ColorModel originalModel)
{
super(originalModel.getPixelSize());
this.originalModel = originalModel;
}

// The amount of gray is the max of the red, green, and blue
protected int getGrayLevel(int pixel)
{
return Math.max(originalModel.getRed(pixel),
Math.max(originalModel.getGreen(pixel),
originalModel.getBlue(pixel)));
}

// Leave the alpha values untouched
public int getAlpha(int pixel)
{
return originalModel.getAlpha(pixel);
}

// Since gray requires red, green and blue to be the same,
// use the same gray level value for red, green, and blue

public int getRed(int pixel)
{
return getGrayLevel(pixel);
}

public int getGreen(int pixel)
{
return getGrayLevel(pixel);
}

public int getBlue(int pixel)
{
return getGrayLevel(pixel);
}

// Normally, this method queries the red, green, blue and
// alpha values and returns them in the form 0xaarrggbb. To
// keep from computing the gray level 3 times, we just override
// this method, get the gray level once, and return it as the
// red, green, and blue, and add in the original alpha value.

public int getRGB(int pixel)
{
int gray = getGrayLevel(pixel);
return (getAlpha(pixel) << 24) + (gray << 16) +
(gray << 8) + gray;
}
}