How can I create a grayscale image from a color image?

Bill Day

BufferedImage is a powerful new capability provided by Java 2. You can use the BufferedImage to access the pixel-by-pixel RGB information to decide if the pixels fall within some arbitrary desired color range, then set them to whatever values you like.

If you have a BufferedImage, there's an operation that will do the color conversion for you. Here's a simple example that shows how you can convert any BufferedImage to grayscale.

public static BufferedImage convertToGrayscale(BufferedImage source) { 
     BufferedImageOp op = new ColorConvertOp(
       ColorSpace.getInstance(ColorSpace.CS_GRAY), null); 
     return op.filter(source, null);

You can create grayscale images some other way if you like. So long as your R, G, and B values for a given pixel are the same (for instance, all '10' or all '137'), you will have a gray pixel.