图像处理工具 ImageIO 忽略 PNG 图片的透明度通道。

5

看起来使用ImageIO.read加载的PNG文件会忽略alpha通道。(我尝试过JRE 6 update 20)

是个bug吗?

示例:

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

}


1
怎么样发布一个简化的应用程序来演示这个行为? - Stephen C
3个回答

4

您如何知道它忽略了alpha通道。下面的代码产生了这个截图:

enter image description here

代码:

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

2

根据我的经验-在JDK 1.6.0_21上测试,Java imageio png解码器部分支持透明度。它支持具有额外alpha通道的24位全彩色图像(每像素完全为32位),以及带有tRNS干线的索引颜色图像,其中包括可以与现有RGB调色板组合的Alpha映射来定义哪种颜色是透明的。但是,它不支持具有tRNS干线的24位RGB,该干线包括用于图像的单个透明RGB颜色值。也许您的图像是这些不受imageio支持的格式之一。


1

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接