Java 在缓冲区上绘制图像的透明度

Java 在缓冲区上绘制图像的透明度,java,Java,你好 我试着用图形在缓冲策略上画画。这幅画有一个透明的背景,如果我在屏幕上画它,透明区域就会变成黑色 蓝色的东西是我想画的图像,但是没有黑色的部分(在原始图片中它们不在那里) 我就是这样画的: BufferedImage image = loadImage(path); g.drawImage(image, x, y, null); public BufferedImage loadImage(String path) { ImageIcon icon = new Ima

你好

我试着用
图形在
缓冲策略
上画画。这幅画有一个透明的背景,如果我在屏幕上画它,透明区域就会变成黑色

蓝色的东西是我想画的图像,但是没有黑色的部分(在原始图片中它们不在那里)

我就是这样画的:

BufferedImage image = loadImage(path);

g.drawImage(image, x, y, null);

public BufferedImage loadImage(String path) {

        ImageIcon icon = new ImageIcon(this.getClass().getClassLoader().getResource(path));

        BufferedImage image = new BufferedImage(icon.getIconWidth(), icon.getIconHeight(), BufferedImage.TYPE_INT_RGB);

        Graphics g = image.createGraphics();

        icon.paintIcon(null, g, 0, 0);
        g.dispose();

        return image;

}

Andreas的评论是正确的,但应该是
ARGB
,而不是
RGBA

要执行此操作,只需更改
buffereImage。在此行中键入\u INT\u RGB

BufferedImage image=new BufferedImage(icon.getIconWidth(),icon.getIconHeight(),BufferedImage.TYPE_INT_RGB)

缓冲区映像。键入\u INT\u ARGB

BufferedImage image=new BufferedImage(icon.getIconWidth(),icon.getIconHeight(),BufferedImage.TYPE_INT_ARGB)


根据您的评论进行编辑,以下是完整答案:

除了作为
TYPE_INT_ARGB
创建缓冲图像外,还需要使用如下图形将AlphaComposite
SRC_OVER
应用于缓冲图像2d:

public static BufferedImage loadImage(String path)
{
    ImageIcon icon = new ImageIcon(path);

    //using TYPE_INT_ARGB
    BufferedImage image = new BufferedImage(icon.getIconWidth(), icon.getIconHeight(), BufferedImage.TYPE_INT_ARGB);    

    //changed to G2D change here
    Graphics2D g2d = image.createGraphics();
    //get alpha
    AlphaComposite ac = AlphaComposite.getInstance(AlphaComposite.SRC_OVER);  
    //set alpha
    g2d.setComposite(ac);

    icon.paintIcon(null, g2d, 0, 0);
    g2d.dispose();

    return image;
}

用源代码详细解释你的问题,并提供你想要的图像作为一个好的解决方案。@Programmer I更新了它:)你的图像没有alpha通道。使用BuffereImage.TYPE_INT_RGBA instead我尝试过,但没有改变,仍然是黑色背景-您还需要使用Graphics2D将AlphaComposite
SRC_OVER应用于缓冲图像。请参阅上面的“使用工作代码进行编辑”。