A rather dull worKLOG. This is just a scratchpad for solutions to IT problems that might be useful to someone else. Expect no opinions, no brilliant insights and definitely no pictures of pets or children. Expect stack traces, code snippets and other hints for the Google Indexer.

Thursday, January 04, 2007

Problems with Image loading in Java


I'm trying to load images in Java for use in icons with the following:
new ImageIconr(url)

Mostly, this works fine. But just once in a while it fails with:

Uncaught error fetching image:
java.lang.SecurityException
at java.lang.SecurityManager.checkPermission(SecurityManager.java:562)
at java.lang.SecurityManager.checkConnect(SecurityManager.java:1078)
at sun.awt.image.URLImageSource.checkSecurity(URLImageSource.java:81)
at sun.awt.image.ImageRepresentation.imageComplete(ImageRepresentation.j
ava:597)
at sun.awt.image.InputStreamImageSource.errorConsumer(InputStreamImageSo
urce.java:131)
at sun.awt.image.InputStreamImageSource.setDecoder(InputStreamImageSourc
e.java:331)
at sun.awt.image.InputStreamImageSource.doFetch(InputStreamImageSource.j
ava:252)
at sun.awt.image.ImageFetcher.fetchloop(ImageFetcher.java:172)
at sun.awt.image.ImageFetcher.run(ImageFetcher.java:136)

What's worse, surrounding the code with a try-catch block doesn't save you - the application simply locks up. Note that this
only happens when running under a SecurityManager such as under WebStart. It seems there's a bug in the JDK
http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4881229
which means that if the URL gets redirected with an http 302, then an internal thread in the JDK will fail. This
is pretty hopeless - can't fix it, can't trap it.

The workaround is to use a different part of the API. Instead of constructing an Icon from a URL, you first get an Image using
Image im = ImageIO.read(url);
then construct an icon from that:
new Icon(im);