【问题标题】:Changing icon color in java在java中更改图标颜色
【发布时间】:2022-03-01 20:05:21
【问题描述】:

所以我正在使用一个可以根据用户要求更改主题的程序。现在我必须根据主题更改图标颜色。 假设我有一个图标“Cut.png”,所以它将有一个大的透明区域和一些黑线所以我希望这些线(任何颜色)更改为所需的颜色并且透明区域相同。我正在尝试使用缓冲图像,我跳过了具有 0 alpha 的像素,但输出给了我一个完全黑色的图标:(

这里是部分代码:

BufferedImage buf = ImageIO.read(Image Path);
int red = Color.RED.getRBG();
for(....)//Loop for Row
    for(....)//Loop for column
    {
      Color col = new Color(buf.getRGB(x,y));
      if(col.getAlpha() == 0) continue;
      buf.setRGB(x,y,red);
    }

我的程序完全相同,我希望它应该忽略透明像素并将彩色像素更改为红色,但产生的输出完全是黑色:(

感谢您的帮助:)

【问题讨论】:

  • "程序完全相同相同" - 肯定不是完全相同相同,这永远不会编译 (getRBG()/getRGB(); ...) - 如果包含 minimal reproducible example 更好 - 另请参阅 Color(int) 构造函数的文档:“创建 不透明 sRGB 颜色” - 尝试 @987654327 @

标签: java image bufferedimage javax.imageio


【解决方案1】:

确保您的目标图像也是透明的

BufferedImage img = ImageIO.read(Main.class.getResource("/images/ArrowRight.png"));
BufferedImage coloredImg = new BufferedImage(img.getWidth(), img.getHeight(), BufferedImage.TYPE_INT_ARGB);
Color targetColor = Color.RED;
for (int y = 0; y < img.getHeight(); y++) {
    for (int x = 0; x < img.getWidth(); x++) {
        int rgb = img.getRGB(x, y);
        Color color = new Color(rgb, true);
        if (color.getAlpha() > 0) {
            Color pixelColor = new Color(targetColor.getRed(), targetColor.getGreen(), targetColor.getBlue(), color.getAlpha());
            coloredImg.setRGB(x, y, pixelColor.getRGB());
        }
    }
}

JPanel pane = new JPanel();
pane.add(new JLabel(new ImageIcon(img)));
pane.add(new JLabel(new ImageIcon(coloredImg)));

JOptionPane.showMessageDialog(null, pane);

同样,您也可以使用Graphics API 直接绘制到目标图像上

BufferedImage img = ImageIO.read(Main.class.getResource("/images/ArrowRight.png"));
BufferedImage coloredImg = new BufferedImage(img.getWidth(), img.getHeight(), BufferedImage.TYPE_INT_ARGB);
Color targetColor = Color.RED;

Graphics2D g2d = coloredImg.createGraphics();
g2d.setColor(targetColor);

for (int y = 0; y < img.getHeight(); y++) {
    for (int x = 0; x < img.getWidth(); x++) {
        int rgb = img.getRGB(x, y);
        Color color = new Color(rgb, true);
        if (color.getAlpha() > 0) {
            float alpha = color.getAlpha() / 255.0f;
            g2d.setComposite(AlphaComposite.SrcOver.derive(alpha));
            g2d.fillRect(x, y, 1, 1);
        }
    }
}

g2d.dispose();

JPanel pane = new JPanel();
pane.add(new JLabel(new ImageIcon(img)));
pane.add(new JLabel(new ImageIcon(coloredImg)));

JOptionPane.showMessageDialog(null, pane);

或者您也可以只为图像“着色”,例如 example

【讨论】:

  • 哇,它真的奏效了 :) 感谢您的热心帮助和非常快速的回复?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-07-09
  • 2017-06-01
  • 1970-01-01
相关资源
最近更新 更多