问题
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.");
}
}
}
Probably the image should be loaded in a different way?
Thanks!
回答1:
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 );
回答2:
This Exception is thrown from a separate thread, not the main thread. Actually your application execution completes successfully.
回答3:
As @MikeNakis said, a new Thread
is spawned. In fact, ImageIcon
delegates the image loading to a MediaTracker
which has a spawned Thread
and exposes methods to ImageIcon
to get image status
Try using getImageLoadStatus()
which returns the underlying status of the image in the MediaTracker
You can not get rid of the exception, as exceptions are catched by the `MediaTracker̀ and sent to sytem err. By the way, there is probably a mean to redirect system err elsewhere and keep your app console clean
来源:https://stackoverflow.com/questions/8656952/how-to-catch-sun-awt-image-pngimagedecoderpngexception