3

我在图像透明度方面遇到问题。如下:

我有 image1,我需要在它上面重叠 image2。image2 是具有透明度的 png。我想创建一个带水印的图像,这将是 image1 之上的透明 image2。

当我打开具有透明度的 image2 并将其放入 JFrame 中只是为了预览它时,它会以透明度打开。但是当我使用 BufferImage 对象的方法 getRGB 来获取 image2 的像素并使用 setRGB 将其覆盖在 image1 上时,image2 会失去透明度并获得白色背景。这是代码:

public class Test {
    public static void main(String[] args) throws IOException {
        BufferedImage image = ImageIO.read(new File("c:/images.jpg"));
        BufferedImage image2 = ImageIO.read(new File("c:/images2.png"));
        int w = image2.getWidth();
        int h = image2.getHeight();
        int[] pixels = image2.getRGB(0, 0, w, h, null, 0, w);
        image2.setRGB(0, 0, w, h, pixels ,0 ,w);
        // here goes the code to show it on JFrame
    }
}

请,有人可以告诉我我做错了什么吗?我注意到这段代码正在丢失 image2 的 alpha。我怎样才能让它不失去阿尔法?

4

1 回答 1

3

问题在于 setPixel 将对直接接收像素的图像使用编码,而无需解释原始图像的图形上下文。如果您使用图形对象,则不会发生这种情况。

尝试:

public static void main(String[] args) throws IOException {
    BufferedImage image = ImageIO.read(new File("c:/images.jpg"));
    BufferedImage image2 = ImageIO.read(new File("c:/images2.png"));

    int w = image2.getWidth();
    int h = image2.getHeight();

    Graphics2D graphics = image.createGraphics();
    graphics.drawImage(image2, 0, 0, w, h, null);
    graphics.dispose();
    // here goes the code to show it on JFrame
}
于 2012-12-02T16:21:13.640 回答