Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to turn ImageIcon to gray on Swing

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));
like image 671
Alfergon Avatar asked Jan 16 '13 12:01

Alfergon


1 Answers

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);
}
like image 183
trashgod Avatar answered Oct 10 '22 02:10

trashgod