How to turn ImageIcon to gray on Swing

我的未来我决定 提交于 2019-12-29 07:33:24

问题


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));

回答1:


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

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

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

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

/**
 * @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);
}



回答2:


You can use the following:

ImageIcon icon = new ImageIcon("yourFile.gif");
Image normalImage = icon.getImage();
Image grayImage = GrayFilter.createDisabledImage(normalImage);


来源:https://stackoverflow.com/questions/14358499/how-to-turn-imageicon-to-gray-on-swing

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!