确保您的目标图像也是透明的
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