如何捕获sun.awt.image.PNGImageDecoder $ PNGException? [英] How to catch sun.awt.image.PNGImageDecoder$PNGException?

查看:104
本文介绍了如何捕获sun.awt.image.PNGImageDecoder $ PNGException?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

How to catch the following exception that is printed to the error console when trying to load a corrupted PNG file:

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)

以下代码使以上输出显示在错误控制台中。但是永远不会捕获到异常:

Following code makes the above output appear in the error console. But the exception is never caught:

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 [] 数组)创建图像,然后 then 正常,创建 ImageIcon

I'm not familiar with ImageIcon but you could simply first try to create an image from your source (your byte[] array) and then, if everything goes fine, create the 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:

and then if everything goes fine your create the ImageIcon:

ImageIcon ii = new ImageIcon( img );

这篇关于如何捕获sun.awt.image.PNGImageDecoder $ PNGException?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆