如何在Swing中将ImageIcon转换为灰色

11

我想知道在Swing中是否有一种方法可以将ImageIcon转换成灰度图像,就像这样:

component.setIcon(greyed(imageIcon));
2个回答

14
GrayFilter.createDisabledImage()的一个限制是,它旨在为来自不同外观实现的图标创建禁用外观。使用此示例中的ColorConvertOp,以下图像对比效果:

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://dev59.com/yWYq5IYBdhLWcg3wmRoD
 * @see https://dev59.com/OmfWa4cB1Zd3GeqPl_OJ#12228640
 */
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);
}

我目前只需要它来禁用图标,但是您的答案比我的好得多,所以我会选择那个。非常感谢您的出色答案。 - Alfergon
不客气,谢谢。我不会说“更好”,只是“互补”。 :-) - trashgod
4
对上面代码的小改进:使用 gc.createCompatibleImage(w, h, Transparency.TRANSLUCENT); 而不是 gc.createCompatibleImage(w, h); 来保持原始图标的半透明性。 - Huxi

11

你可以使用以下内容:

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

2
@DavidKroukamp 在 Stack Exchange 网络上提问和回答问题是鼓励的,更多信息请参见 http://meta.stackexchange.com/a/17847/140951(如果您需要其他参考资料,我可以提供)。 - casperOne

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接