Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ImageIO ignores PNG alpha channel

It seems that PNG loaded with ImageIO.read ignore the alpha channel. (I tried with JRE 6 update 20)

Bug ?

Example :

public class Test extends JFrame
{

public Test()
{
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    JButton b = new JButton("Test");
    try
    {
        b.setIcon(new ImageIcon(ImageIO.read(new File("D:\\image.png"))));
    }
    catch (IOException e2)
    {
    }
    b.addActionListener(new ActionListener()
    {
        public void actionPerformed(ActionEvent e)
        {
        }
    });
    getContentPane().add(b, BorderLayout.CENTER);
    setSize(500,500);
    setVisible(true);
}

/**
 * @param args
 */
public static void main(String[] args)
{
    new Test();
}

}

like image 762
Arutha Avatar asked Jan 10 '11 13:01

Arutha


2 Answers

How do you know that it ignores the alpha channel. The code below produces this screenshot:

enter image description here

Code:

public static void main(String[] args) throws Exception {

    URL url = new URL("http://upload.wikimedia.org/" +
                   "wikipedia/commons/4/47/PNG_transparency_demonstration_1.png");
    Image image = ImageIO.read(url);

    JPanel bgPanel = new JPanel(new BorderLayout()) {{
            setOpaque(false);
        }
        protected void paintComponent(Graphics g) {
            Rectangle r = g.getClipBounds();
            // paint bg
            int s = 10;
            for (int y = r.y / s; y < r.y + r.height; y += s) {
                int o = (y % (2*s) == 0 ? s : 0);
                for (int x = r.x / s + o; x < r.x + r.width; x += 2*s)
                    g.fillRect(x, y, s, s);
            }
            super.paintComponent(g);
        }
    };

    bgPanel.add(new JLabel(new ImageIcon(image)) {{
        setOpaque(false);
    }});

    JFrame frame = new JFrame("Test");
    frame.add(bgPanel);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setSize(350, 300);
    frame.setVisible(true);
}
like image 51
dacwe Avatar answered Oct 15 '22 08:10

dacwe


Through my experience - tested with JDK 1.6.0_21, Java imageio png decoder supports transparency partially. It supports 24-bit full color image with an additional alpha channel (totally 32-bit per pixel), as well as indexed color image with tRNS trunk which includes an alpha map that can be combined with the existing RGB color palette to define which color is transparent. But it DOES NOT support 24-bit RGB with a tRNS trunk that includes a single transparent RGB color value for the image. Perhaps your image is one of such formats that are not supported by imageio.

like image 2
dragon66 Avatar answered Oct 15 '22 09:10

dragon66