ImageCacher

As I seem to get a lot of portfolio jobs I’m constantly trying to find the best way to load images, they need to download fast, but still be high quality and not leave the user watching a progress bar as the large images gradually download. So after some thought and some blog reading I’ve created an ImageCacher Class in ActionScript 3.

The class acts like a proxy for image requests, so instead of using the Loader class to load an image you go through the ImageCacher class. The principle is almost the same, the ImageCacher creates a Loader instance, adds event listeners and then loads the image. Once the image download is complete, ImageCacher also saves the BitmapData of the image and the url of the image so that next time an image request is made, ImageCacher checks to see if the image from that url has already been loaded and if so, returns the BitmapData immediately rather than making another call to the server.

I’ve created two demos, the first shows the effect of the ImageCacher by instantly returning the BitmapData of an image that has already been loaded once. The second is version 0.2 of the ImageCacher which now includes a preload() method where all the images are preloaded initially so when you click to load an image the result is instantaneous.

Eventually as you can imagine all that BitmapData will build up in the swf’s memory as it is running. So ImageCacher, by default, also clears the last 20% of all image requests every 5 minutes. As far as I can tell the Class is now working fine although I haven’t used it on a job yet – my current job is getting about to get the ImageCacher treatment. One problem I had initially was the ImageCacher was only working on absolute links. It turns out the error was because, even though you may pass in a relative link ie “/images/my-first-image.jpg” once the image is loaded the url being stored was it’s absolute link from the Loader class. The two links didn’t match so a new image was being loaded every time. To solve this I store the url from the request in a temporary variable, then once the image download is complete I store that variable rather than the url from the Loader class. Job done!

Changelog:
0.1 – The initial class which caches images
0.2 – Added preloader() method
0.3 – Calling reset() will now close any active image downloads

Demos:
http://www.lukesturgeon.co.uk/labs/demos/imagecacher/demo.swf
http://www.lukesturgeon.co.uk/labs/demos/imagecacher/preloader.swf

Source:
http://www.lukesturgeon.co.uk/labs/demos/imagecacher/ImageCacher_0_1.zip
http://www.lukesturgeon.co.uk/labs/demos/imagecacher/ImageCacher_0_2.zip
http://www.lukesturgeon.co.uk/labs/demos/imagecacher/ImageCacher_0_3.zip 

If anyone wants to try out this class, extend it or break it, feel free and please let me know how it goes.