How to catch sun.awt.image.PNGImageDecoder$PNGException?

前端 未结 3 623
别那么骄傲
别那么骄傲 2021-01-25 00:04

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: i         


        
3条回答
  •  情话喂你
    2021-01-25 00:49

    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.

    Like this:

        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...
        }
    

    and then if everything goes fine your create the ImageIcon:

    ImageIcon ii = new ImageIcon( img );
    

提交回复
热议问题