如何为ImageIcon着色

时间:2015-05-25 18:37:23

标签: java graphics bufferedimage imageicon tint

我如何将通过此处传递的图标着色为不同的颜色?说我想拍一张白色图片并让它变暗一点。我已经研究过BufferedImages等,但我似乎无法找到适合我正在使用的设置的任何内容。我还应该注意到,如果这会产生影响,我会将图像绘制到JLabel上。

以下是我使用的来源,以便您可以了解我正在使用的内容。

public class Icon extends ImageIcon{

    private int scale = 1;
    private boolean mirror = false;

    public Icon(URL url) throws IOException{
        super(ImageIO.read(url));
    }

    public void setScale(int scale){
        this.scale = scale;
    }

    @Override
    public synchronized void paintIcon(Component c, Graphics g, int x, int y) {
        Graphics2D g2 = (Graphics2D)g.create();
        int height = 0, width = this.getIconWidth(), x1 = 1;
        if(mirror || scale != 1){
            height = -this.getIconHeight();
        }
        if(mirror){
            x1 = -1;
        }else{
            width = 0;
        }
        g2.translate(width * scale, height);
        g2.scale(x1 * scale, 1 * scale);
        super.paintIcon(c, g2, x, y);
    }

    public boolean isMirror() {
        return mirror;
    }    

    public void setMirror(boolean mirror) {
        this.mirror = mirror;
    }
}

1 个答案:

答案 0 :(得分:1)

您需要创建一个新的BufferedImage以进行转换:

public BufferedImage colorImage(BufferedImage loadImg, int red, int green, int blue) {
    BufferedImage img = new BufferedImage(loadImg.getWidth(), loadImg.getHeight(),
        BufferedImage.TRANSLUCENT);
    Graphics2D graphics = img.createGraphics(); 
    Color newColor = new Color(red, green, blue, 0 /* alpha needs to be zero */);
    graphics.setXORMode(newColor);
    graphics.drawImage(loadImg, null, 0, 0);
    graphics.dispose();
    return img;
}