3
votes

I'm having problems with image transparency. It's the following:

I have image1 and I need to overlap image2 over it. image2 is png with transparency. I want to create an image with watermark, that would be transparent image2 on top of image1.

When I open image2, that has transparency, and put it in a JFrame just to preview it, it opens with transparency. But when I use a BufferImage object's method getRGB to get image2's pixels and I use setRGB to overlay it over image1, image2 loses transparency and gets white background. Here's the code:

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
    }
}

Please, can someone tell me what I'm doing wrong? I noticed that this code is losing image2's alpha. How could I make it to not lose alpha?

1

1 Answers

3
votes

The problem's that setPixel will use the encoding for the image that receives the pixel in a direct way, without interpreting the graphical context for the original image. That won't happen if you use the graphics object.

Try:

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
}