ImageIO忽略PNG alpha通道

Aru*_*tha 5 java png alpha image image-processing

似乎装有ImageIO.read的PNG忽略了alpha通道.(我试过JRE 6更新20)

错误?

示例:

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();
}
Run Code Online (Sandbox Code Playgroud)

}

dac*_*cwe 5

你怎么知道它忽略了alpha通道.以下代码生成此屏幕截图:

在此输入图像描述

码:

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);
}
Run Code Online (Sandbox Code Playgroud)


ism*_*ail 1

您可以使用Sixlegs Java PNG Decoder,它没有 alpha 透明度错误。作为参考,Sun Java Bug #6371389讨论了 PNG Alpha 通道的类似问题。