如何将ImageIcon的黑色像素更改为白色像素?

时间:2014-12-06 17:31:44

标签: java image swing colors bufferedimage

我知道我可以在照片处理软件中进行更改,但我想学会以编程方式进行更改,以便将其更改为我希望的任何颜色。


首先,我想说我一直在寻找解决方案大约两个小时,我找不到适合我的解决方案,或者找不到解决我确切问题的解决方案。

我从互联网上下载了一些图标,它们原本是黑色的,带有透明背景,这对菜单栏和东西很有用。但是,在我的工具栏上很难注意到它们,我想将这些图标上的黑色更改为白色。这是an edited screenshot of what I'm trying to achievea screenshot of what I achieve。 (对不起链接,我需要至少10个声望来发布图片。

这是我的Utility类负责失败的工作:

public final class Utility{
    public static ImageIcon replaceIconColor(ImageIcon icon, Color oldColor, Color newColor){
        BufferedImage image = iconToImage(icon);

        for(int y = 0; y < image.getHeight(); y++){
            for(int x = 0; x < image.getWidth(); x++){
                Color pixel = new Color(image.getRGB(x, y));
                if((pixel.getRed() == oldColor.getRed()) && (pixel.getGreen() == oldColor.getGreen()) && (pixel.getBlue() == oldColor.getBlue()) && (pixel.getAlpha() == oldColor.getAlpha())){
                    image.setRGB(x, y, newColor.getRGB());
                }
            }
        }

        return new ImageIcon(image);
    }

    public static BufferedImage iconToImage(ImageIcon icon){
        return Resources.loadImage(icon.getDescription());
    }
}

我不确定您是否需要资源加载类代码,但我认为它只能帮助您完全理解我的问题并能够帮助我最好的帮助。所以,这是我的Resources类代码片段:

public static ImageIcon loadImageIcon(String fileName){
    URL imageURL = Resources.class.getResource("/Resources/Images/" + fileName);
    ImageIcon imageIcon = new ImageIcon(imageURL);
    imageIcon.setDescription(fileName);
    return imageIcon;
}

public static BufferedImage loadImage(String fileName){
    URL imageURL = Resources.class.getResource("/Resources/Images/" + fileName);
    BufferedImage image = null;

    try{
        image = ImageIO.read(imageURL);
    }catch(IOException e){
        e.printStackTrace();
    }

    return image;
}

如果在互联网上某处确实有解决方案,我很抱歉,但我找不到它。嗯,就是这样。我认为我足够具体。

提前谢谢!

1 个答案:

答案 0 :(得分:1)

两种方法很常见:

  • 根据需要使用BufferedImagegetRGB()example循环遍历setRGB()

  • 使用LookupOp,如引用的示例所示here

相关问题