Home > Articles

  • Print
  • + Share This
This chapter is from the book

ColorConvertOp

This BufferedImageOp implementation performs a pixel-by-pixel color conversion of the source image into the destination image. This particular image-processing operation has an interesting feature: It transforms a given pixel from one color model to another. To do this, the filter needs the color value of only this single pixel, which means that it is possible to use the same image as both the source and the destination.

Converting an image from one color model to another has little practical use if you are not building an advanced imaging tool. And it is definitely useless if terms like "CMYK," "sRGB," and "Adobe RGB 1998 color profile" mean nothing to you. Color spaces are very useful, but describing them and their applications goes way beyond the scope of this book. Even so, we can use a ColorConvertOp to create something more basic and potentially useful to us: a grayscale version of a source image.

You first need to create a ColorSpace instance that represents the color model to which you want to convert your image. A ColorSpace can be instantiated by invoking ColorSpace.getInstance(int) and passing one of the five following constants:

ColorSpace.CS_CIEXYZ
ColorSpace.CS_GRAY
ColorSpace.CS_LINEAR_RGB
ColorSpace.CS_PYCC
ColorSpace.CS_sRGB

You might have already guessed which one is best suited to our purpose of performing a grayscale conversion:

BufferedImage dstImage = null;
ColorSpace colorSpace = ColorSpace.getInstance(
    ColorSpace.CS_GRAY);
ColorConvertOp op = new ColorConvertOp(colorSpace, null);
dstImage = op.filter(sourceImage, null);

Similar to AffineTransformOp, ColorConvertOp can use a set of RenderingHints to control the quality of the color conversion and the dithering. Figure 8-5 shows the result of the our color conversion.

Figure 8-5

Figure 8-5 ColorConvertOp can be used to create a grayscale version of an image.

Last but not least, it is important to know that performing such a conversion on an image may make it incompatible with your graphics display hardware, thus hurting the performance if you need to paint the filtered image to the Swing window.

You may want to convert the image to be a compatible image instead for general usage. See Chapter 3 for more information.

  • + Share This
  • 🔖 Save To Your Account