【问题标题】:How to Change ImageIcon's Black Pixels to White Pixels?如何将 ImageIcon 的黑色像素更改为白色像素?
【发布时间】:2015-02-04 17:13:16
【问题描述】:

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


首先,我想说的是,我已经搜索了大约两个小时的解决方案,但找不到适合我的解决方案,或者解决我确切问题的解决方案。

我从网上下载了一些图标,它们最初是黑色的,背景是透明的,这对菜单栏和其他东西很有用。但是,在我的工具栏上很难注意到它们,我想将这些图标上的黑色更改为白色。这里是an edited screenshot of what I'm trying to achieve,这里是a screenshot of what I achieve。 (抱歉链接,我需要至少 10 个声望才能发布图片。

这是我的实用程序类,它负责失败的工作:

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

我不确定您是否需要资源加载类代码,但我认为它只能帮助您充分理解我的问题并能够尽您所能帮助我。所以,这是我的资源类代码 sn-p:

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

如果互联网上确实有解决方案,我深表歉意,但我找不到。嗯,就是这样。我想我已经足够具体了。

提前致谢!

【问题讨论】:

    标签: java image swing colors bufferedimage


    【解决方案1】:

    两种方法很常见:

    • 根据需要使用getRGB()setRGB() 循环遍历BufferedImage,用于example

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

    【讨论】:

      猜你喜欢
      • 2023-01-13
      • 1970-01-01
      • 2021-01-27
      • 2019-12-13
      • 2015-05-05
      • 2018-09-28
      • 1970-01-01
      • 2015-02-13
      • 2020-10-24
      相关资源
      最近更新 更多