10

I would like to know if there is some way in Swing to turn an ImageIcon to gray scale in a way like:

component.setIcon(greyed(imageIcon));
Andrew Thompson
  • 163,965
  • 36
  • 203
  • 405
Alfergon
  • 4,891
  • 5
  • 34
  • 51

2 Answers2

14

One limitation of GrayFilter.createDisabledImage() is that it is designed to create a disabled appearance for icons across diverse Look & Feel implementations. Using this ColorConvertOp example, the following images contrast the effect:

GrayFilter.createDisabledImage(): com.apple.laf.AquaLookAndFeel image

ColorConvertOp#filter(): com.apple.laf.AquaLookAndFeel image

GrayFilter.createDisabledImage(): com.sun.java.swing.plaf.nimbus.NimbusLookAndFeel image

ColorConvertOp#filter(): com.sun.java.swing.plaf.nimbus.NimbusLookAndFeel image

/**
 * @see https://stackoverflow.com/q/14358499/230513
 * @see https://stackoverflow.com/a/12228640/230513
 */
private Icon getGray(Icon icon) {
    final int w = icon.getIconWidth();
    final int h = icon.getIconHeight();
    GraphicsEnvironment ge =
        GraphicsEnvironment.getLocalGraphicsEnvironment();
    GraphicsDevice gd = ge.getDefaultScreenDevice();
    GraphicsConfiguration gc = gd.getDefaultConfiguration();
    BufferedImage image = gc.createCompatibleImage(w, h);
    Graphics2D g2d = image.createGraphics();
    icon.paintIcon(null, g2d, 0, 0);
    Image gray = GrayFilter.createDisabledImage(image);
    return new ImageIcon(gray);
}
Community
  • 1
  • 1
trashgod
  • 196,350
  • 25
  • 213
  • 918
  • I currently just needed it for disabled icons, but your answer is way better mine, so I'll choose that one. Thank you for the great answer. – Alfergon Jan 16 '13 at 15:02
  • You are welcome, and thank you. I won't say _better_, just _complementary_. :-) – trashgod Jan 16 '13 at 15:16
  • 4
    Small enhancement to the code above: use `gc.createCompatibleImage(w, h, Transparency.TRANSLUCENT);` instead of `gc.createCompatibleImage(w, h);` to keep the original icons translucency. – Huxi Oct 24 '14 at 13:09
10

You can use the following:

ImageIcon icon = new ImageIcon("yourFile.gif");
Image normalImage = icon.getImage();
Image grayImage = GrayFilter.createDisabledImage(normalImage);
Alfergon
  • 4,891
  • 5
  • 34
  • 51
  • 2
    @DavidKroukamp Asking and answering your question is encouraged on the Stack Exchange network, see - http://meta.stackexchange.com/a/17847/140951 (and I have other references if you want them) for more. – casperOne Jan 16 '13 at 12:44