Filtering the RGB Values in an Image - Java 2D Graphics

Java examples for 2D Graphics:Color RGB

Description

Filtering the RGB Values in an Image

Demo Code


import java.awt.Image;
import java.awt.Toolkit;
import java.awt.image.FilteredImageSource;
import java.awt.image.ImageFilter;
import java.awt.image.RGBImageFilter;

import javax.swing.ImageIcon;

public class Main {
  public static void main(String[] argv) {
    // Get image/*from  w  ww. j  a  va  2 s  .  c o  m*/
    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);
  }

}

class GetRedFilter extends RGBImageFilter {
  public GetRedFilter() {
    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;
  }
}

Related Tutorials