The Greyscale Filter Example

The following filter converts an image to greyscale. The red, green, and blue colors in each pixel are averaged. Then the resulting color is set to a grey scale with that average intensity.

import java.awt.image.*;


public class GreyFilter extends RGBImageFilter {

  protected boolean canFilterIndexColorModel = true;

  public int filterRGB(int x, int y, int rgb) {

    int red = rgb & 0x00FF0000;
    red >>>= 16;
    int green =   rgb & 0x0000FF00;
    green >>>= 8;
    int blue =   rgb & 0x0000FF;
    int grey = (red + green + blue)/3;
    return 
     (0x000000FF << 24) | (grey << 16) | (grey << 8) | grey; 
    
  }

}
Notice that before averaging you have to shift the red and green components to the right 16 and 8 bits respectively. This forces them into the range 0 to 255. The >>> operator shifts right without sign extension.

import java.awt.*;
import java.awt.image.*;
import java.applet.*;


public class GreyImage extends Applet {

  private Image picture;

  public void init() {
  
    String filename = this.getParameter("imagefile");
    if (filename != null) {
      Image source = this.getImage(getDocumentBase(), filename);
      this.picture = this.createImage(
       new FilteredImageSource(source.getSource(), new GreyFilter()));
    }
  
  }
  
  public void paint (Graphics g) {
   
    if (this.picture != null) {
      g.drawImage(this.picture, 0, 0, this);
    }
    else {
      g.drawString("Missing Picture", 20, 20);
    }
    
  }

}

Previous | Next | Top
Last Modified April 10, 2000
Copyright 1997, 2000 Elliotte Rusty Harold
elharo@metalab.unc.edu