简体   繁体   中英

ImageIO.read(png) losing its transparency

I've tested my image when using (1) and it's of type TYPE_3BYTE_BGR while it's a transparent image, when using (2) my image appears with transparency, can someone explain me where I'm doing a mistake please?

Here's my code:

public static void main(String[] args){

    Frame frame = new Frame();
    frame.setSize(200, 200);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.getContentPane().setLayout(null);
    frame.getContentPane().setBackground(Color.PINK);
    BufferedImage image;
    try{
        image = ImageIO.read(new File("my_path"));
    }catch(IOException e){
        image = null;
    }
    JLabel label = new JLabel(new ImageIcon("my_path"));
    //JLabel label = new JLabel(new ImageIcon(image));
    frame.getContentPane().add(label);
    label.setBounds(10, 10, 6, 10);
    frame.setVisible(true);

}

Here 's my image.

Thanks in advance!

PS: Btw site must be broken I was not able to paste my code, had to rewrite it, weird.

PS2: Also it's been the second time my "Hi!" as first line gets removed...

Your image file is a 24 bit RGB PNG file, with an optional tRNS chunk, specifying a single RGB color that should be considered transparent (as opposed to a 32 bit RGBA PNG with full alpha channel).

For some reason, the standard PNGImageReader that comes with the JRE does not create a transparent image for RGB PNGs with a tRNS chunk. According the spec, optional chunks (starting with a lowercase letter) can be ignored by a decoder, so this is fully acceptable behavior.

You can, however, read the metadata for the PNG using the ImageIO API, and if there's a tRNS chunk, you can create a transparent BufferedImage and apply the transparency yourself (replacing all RGB values equal to the RGB value from the tRNS chunk). But this is quite some extra work if you just want to read icons bundled with your application.

The easiest fix would be to just store the PNG with either palette and transparency or a full 32 bit RGBA PNG, which are both supported by ImageIO without any more work.

The reason why it works using the "direct" ImageIcon approach, is that ImageIcon uses a completely different PNG decoder than ImageIO, which seemingly does apply the tRNS chunk (in your case, but I don't think has to, so the behavior may vary by JRE or platform, you will have to test).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM