Handling broken images in Flex 2

This post is more than 2 years old.

A friend had a simple question:

If I use the mx:Image tag to load an image and get a 404, how do I handle that?

I jokingly said that the tag should support an onLoad type event so you could check the http status codes. Turn out I wasn't far from the truth. Mike Kollen (The Uber Flex Instructor) sent me this simple block of code as an example of how to handle it:

<mx:Image source="assets/f{dgMovies.selectedItem.FILMID}.gif" ioError="ioError()" id="movieImage" width="110" />

private function ioError():void { movieImage.source = "assets/no_image.gif"; }

Talk about simple. Half of my battles with Flex are simply learning how to do stuff - and luckily when I do learn - it typically turns out to be easy to implement.

Raymond Camden's Picture

About Raymond Camden

Raymond is a senior developer evangelist for Adobe. He focuses on document services, JavaScript, and enterprise cat demos. If you like this article, please consider visiting my Amazon Wishlist or donating via PayPal to show your support. You can even buy me a coffee!

Lafayette, LA https://www.raymondcamden.com

Archived Comments

Comment 1 by Kevin Schmidt posted on 11/22/2006 at 6:13 AM

Ray - I'm finding that most things in Flex are simple and I'm loving it.

Comment 2 by Mark Drew posted on 11/22/2006 at 1:04 PM

Ray, you seem to have not closed a tag or something in your post, the rest of the blog has a courier font ...

Comment 3 by Raymond Camden posted on 11/22/2006 at 1:17 PM

Thanks. Fixed.

Comment 4 by Scott Stroz posted on 11/22/2006 at 6:42 PM

Ray - You can reuse this little snippet elsewhere by rewriting it a bit.

<mx:Image source="assets/f{dgMovies.selectedItem.FILMID}.gif" ioError="ioError(movieImage)" id="movieImage" width="110" />

private function ioError(item:Image):void {
item.source = "assets/no_image.gif";
}

Comment 5 by Raymond Camden posted on 11/22/2006 at 6:54 PM

Makes perfect sense, Scott. Thanks!