The Java Developers Almanac 1.4


Order this book from Amazon.

   
Home > List of Packages > java.awt.image  [21 examples] > Images  [6 examples]

e665. Filtering the RGB Values in an Image

This example demonstrates how to create a filter that can modify any of the RGB pixel values in an image.
    // This filter removes all but the red values in an image
    class GetRedFilter extends RGBImageFilter {
        public GetRedFilter() {
            // When this is set to true, the filter will work with images
            // whose pixels are indices into a color table (IndexColorModel).
            // In such a case, the color values in the color table are filtered.
            canFilterIndexColorModel = true;
        }
    
        // This method is called for every pixel in the image
        public int filterRGB(int x, int y, int rgb) {
            if (x == -1) {
                // The pixel value is from the image's color table rather than the image itself
            }
            // Return only the red component
            return rgb & 0xffff0000;
        }
    }
Here's some code that uses the filter:
    // Get image
    Image image = new ImageIcon("image.gif").getImage();
    
    // Create the filter
    ImageFilter filter = new GetRedFilter();
    FilteredImageSource filteredSrc = new FilteredImageSource(image.getSource(), filter);
    
    // Create the filtered image
    image = Toolkit.getDefaultToolkit().createImage(filteredSrc);

 Related Examples
e660. Creating an Image from an Array of Color-Indexed Pixel Values
e661. Determining If an Image Has Transparent Pixels
e662. Getting the Color Model of an Image
e663. Getting the Transparent Pixel and Number of Colors Used in a GIF Image
e664. Getting a Sub-Image of an Image

See also: Buffered Images    Effects    Volatile Images   


© 2002 Addison-Wesley.