【问题标题】:How to turn ImageIcon to gray on Swing如何在 Swing 上将 ImageIcon 变为灰色
【发布时间】:2012-12-30 18:39:13
【问题描述】:

我想知道 Swing 中是否有某种方法可以将 ImageIcon 转换为灰度,例如:

component.setIcon(greyed(imageIcon));

【问题讨论】:

    标签: java image swing image-processing grayscale


    【解决方案1】:

    GrayFilter.createDisabledImage() 的一个限制是它旨在为各种外观实现中的图标创建禁用外观。使用这个ColorConvertOpexample,下图对比效果:

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

    【讨论】:

    • 我目前只需要它用于禁用图标,但你的答案比我的要好得多,所以我会选择那个。感谢您的精彩回答。
    • 不客气,谢谢。我不会说更好,只是互补。 :-)
    • 对上面代码的小改进:使用gc.createCompatibleImage(w, h, Transparency.TRANSLUCENT);而不是gc.createCompatibleImage(w, h);来保持原来的图标半透明。
    【解决方案2】:

    您可以使用以下内容:

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

    【讨论】:

    • @DavidKroukamp 鼓励在 Stack Exchange 网络上提问和回答您的问题,请参阅 - meta.stackexchange.com/a/17847/140951(如果您需要,我还有其他参考资料)了解更多信息。
    猜你喜欢
    • 2020-11-26
    • 1970-01-01
    • 2015-10-09
    • 1970-01-01
    • 2022-11-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多