开发者

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();
}

}


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

ImageIO ignores PNG alpha channel

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


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.


You can use Sixlegs Java PNG Decoder , it doesn't have alpha transparency bug. For reference, Sun Java Bug #6371389 talks about a similar issue with PNG alpha channels.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜