Java Graphics How to - Filter image color with customized image filter








Question

We would like to know how to filter image color with customized image filter.

Answer

import java.awt.Image;
import java.awt.Toolkit;
import java.awt.image.BufferedImage;
import java.awt.image.FilteredImageSource;
import java.awt.image.RGBImageFilter;
import java.net.URL;
//from   ww w  .  j a va  2  s .  co  m
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;

public class Main {
   public static void main(String[] args)throws Exception {
      String mapUrlPath = "http://www.java2s.com/style/download.png";
         URL mapUrl = new URL(mapUrlPath);
         BufferedImage mapImage = ImageIO.read(mapUrl);
         Image newMapImage = Toolkit.getDefaultToolkit().createImage(
                           new FilteredImageSource(mapImage.getSource(),
                                    new GrayFilter()));
         ImageIcon mapIcon = new ImageIcon(mapImage);
         ImageIcon newMapIcon = new ImageIcon(newMapImage);

         JPanel imagePanel = new JPanel();
         imagePanel.add(new JLabel(mapIcon));
         imagePanel.add(new JLabel(newMapIcon));

         JOptionPane.showMessageDialog(null, imagePanel);
   }
}
class GrayFilter extends RGBImageFilter {
  public int filterRGB(int x, int y, int argb) {
     int r = (argb & 0x00ff0000) >> 0x02;
     int g = (argb & 0x0000ff00) >> 0x08;
     int b = (argb & 0x000000ff);
     int ave = (r + g + b) / 3;

     return ((argb & 0xff000000) | (ave << 0x10 | ave << 0x08 | ave));
  }
}