gpt4 book ai didi

java - 如何捕获 sun.awt.image.PNGImageDecoder$PNGException?

转载 作者:太空宇宙 更新时间:2023-11-04 08:25:23 26 4
gpt4 key购买 nike

如何捕获尝试加载损坏的 PNG 文件时打印到错误控制台的以下异常:

sun.awt.image.PNGImageDecoder$PNGException: invalid depth
at sun.awt.image.PNGImageDecoder.produceImage(Unknown Source)
at sun.awt.image.InputStreamImageSource.doFetch(Unknown Source)
at sun.awt.image.ImageFetcher.fetchloop(Unknown Source)
at sun.awt.image.ImageFetcher.run(Unknown Source)

以下代码使上述输出出现在错误控制台中。但异常永远不会被捕获:

import javax.swing.ImageIcon;

public class TestBadPNG
{

public static void main(String[] args)
{
try
{
new ImageIcon(new byte[] { -119, 80, 78, 71, 13, 10, 26, 10, 0, });
}
catch (Exception e)
{
// This line will not be reached.
System.err.println("Bad image.");
}
}
}

图像可能应该以不同的方式加载?

谢谢!

最佳答案

我不熟悉ImageIcon,但您可以先尝试从源(您的byte[]数组)创建图像,然后然后,如果一切顺利,创建ImageIcon

像这样:

    ByteArrayInputStream bas = new ByteArrayInputStream( new byte[] { -119, 80, 78, 71, 13, 10, 26, 10, 0, } );
Image img = null;
try {
img = ImageIO.read( bas );
} catch (IOException e) {
... // You'll catch that one should it happen...
}

然后,如果一切顺利,您将创建 ImageIcon:

ImageIcon ii = new ImageIcon( img );

关于java - 如何捕获 sun.awt.image.PNGImageDecoder$PNGException?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8656952/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com