Caching images in your Flex application can greatly improve performance and reduce the overhead of loading external resources.

And I’m not simply talking about using the cacheAsBitmap property to improve rendering performance or the cachePolicy property to speed up animations. I’m talking about caching the actual bitmap data of an image.

To get started, you’ll need a hash map to store the image data. A Dictionary or an associative array will also work just fine.

Loading an image for the first time is the same as usual. You create a new Image object and add a listener for the COMPLETE event:

var image : Image = new Image ();
image.addEventListener (Event.COMPLETE, onImageComplete);


Once the image has finished loading, you add a copy of the bitmap data to the hash map using the image URL as the hash key:

private function onImageComplete (event : Event) : void
{
    var image : Image = event.target as Image;

    if (! imageCache.containsKey (image.source))
    {
        var bitmapData : BitmapData = new BitmapData
            (image.content.width, image.content.height, true);

        bitmapData.draw (image.content);

        imageCache.put (image.source, bitmapData);
    }
}


Now we can use the image as many times as we want without ever having to load it again!

To take advantage of this, you’ll need to check the hash map every time you create a new image (or change the source property) to see if you’ve already cached it:

var image : Image = new Image ();
image.addEventListener (Event.COMPLETE, onImageComplete);

if (imageCache.containsKey (imageURL))
{
    image.source = new Bitmap (imageCache.getValue (imageURL));
}
else
{
    image.source = imageURL;
}


And that’s it!

If you have an application that loads a large number of images you may want to limit the number of cached images to prevent the Flash player memory usage from getting out of hand, but in general caching even several dozen large images only results in a slightly increased footprint.

About these ads