1
votes

I have a PNG image with transparency. I used the format because only PNG can support transparency and alpha masks.

My aim is to paint a JPanel with this image and let the transparent regions have the color of the underlying panel, And ultimately do some animations with the image.

How ever I am facing problems, the transparent regions turn out to be solid white color when loaded and painted on the JPanel.

So java does not support transparent images?

class imgpanel extends JPanel{
BufferedImage image,backg;
imgpanel(){
    try {
              image = ImageIO.read(new File("theimage.png"));
              backg = ImageIO.read(new File("backimage.png"));
           } catch (IOException ex) {
                System.out.println("No image found");
   }
    setPreferredSize(new Dimension(400,300));
}
 @Override
    protected void paintComponent(Graphics g) {
        super.paintComponent(g);
        g.drawImage(backg,0,0,null);
        g.drawImage(image, 0, 0, null);
}
}

Thus I am painting the transparent "theimage" onto the opaque "backimage"

2
Could you share the code, what method do you use to add the picture? In some libraries you can add a picture and give the amount of transparency.Arash Saidi
Yes it does support transparency. For a more complete answer you'll need to show some code (like, how you do the drawing).kiheru
For example.trashgod
@kiheru Added code snippetuser2756339
Ah, the same code as two days ago. It actually works correctly as such. Please check the images you are using. I have seen broken behaviour of loading PNGs with indexed colours with some java versions. That's not necessarily the problem, but I'd start looking by using two images in RGBA, both with some translucency.kiheru

2 Answers

2
votes

Yes no problem, do not use palettes, indexed colors.

Try out, whether the images really are transparent, have an alpha component in the color. For instance with a test.html:

<html>
<body>
<div style="background: url(backimage.png)"><img src="theimage.png"></div>
</body>
</html>
1
votes

From my experience ImageIO.read loads the image without the transparency by picking wrong transparency/image type. Therefore I use a workaround - ImageIcon to load it as an Image, which can be drawn into empty BufferedImage with predefined image type BufferedImage.TYPE_INT_ARGB. And don't forget ImageIcon forbids the garbage collector to collect the Image, if the image is not flushed afterwards.

    ImageIcon imageIcon = new ImageIcon(imageAbsolutePath);
    Image tmpImage = imageIcon.getImage();

    BufferedImage image = new BufferedImage(imageIcon.getIconWidth(), imageIcon.getIconHeight(), BufferedImage.TYPE_INT_ARGB);
    image.getGraphics().drawImage(tmpImage, 0, 0, null);
    tmpImage.flush();

    return image;