Hey all,
I wrote an extention to ImageLoader called ImageCache, which takes a snapshot of a loaded bitmap and stores it in a local cache.
That way, when subsequent calls for the same bitmap data are made they can be delivered to the screen instantly without any delays.
Also, I found that this optimization helps with prototyping where I need an external image on the stage "now", but want to write a preloader further down the line. This way the image can be preloaded either before hand, or loaded when required, with the benefit of no-delay drawing if preloaded, and without having to rewrite my display code after the preloader is written.
I think I've covered the correct event hooks, but haven't used LoaderMax much - so if anyone could test/improve this code please let me know.
/**
* VERSION: 1.00
* DATE: 2011-05-26
* AS3
**/
package com.greensock.loading
{
import flash.display.BitmapData;
import flash.display.Bitmap;
import flash.events.Event;
/**
* Extended version of ImageLoader for bitmaps, jpegs, gif, pngs that creates a bitmap cache after each image load and instantly completes subsequent requests for the same URL.
*
* See ImageLoader class for full greensock documentation on using LoaderMax and the ImageLoader.
* Example usage:
*
image = new ImageCacher('images/photo1.jpg', {smoothing:true});
image.load();
*
* author: John Beech, johnbeech@mkv25.net
*/
public class ImageCacher extends ImageLoader
{
private static var _classActivated:Boolean = _activateClass("ImageCacher", ImageCacher, "jpg,jpeg,png,gif,bmp");
protected static var BITMAP_INDEX:Object = {};
public function ImageCacher(urlOrRequest:*, vars:Object=null)
{
super(urlOrRequest, vars);
_type = "ImageCacher";
}
/* Check cache for bitmap first before performing load, unless told to flushContent */
override public function load(flushContent:Boolean=false):void
{
var bitmap:BitmapData = GetBitmap(this.url);
if(bitmap == null || !flushContent)
{
super.load(flushContent);
}
else
{
_content = new Bitmap(bitmap, "auto", Boolean(this.vars.smoothing != false));
super._completeHandler();
}
}
/* On completion take a snapshot of the content and store in cache */
override protected function _completeHandler(e:Event=null):void
{
_determineScriptAccess();
if (!_scriptAccessDenied)
{
var bitmap:BitmapData = new BitmapData(_content.width, _content.height, true, 0x0000FF);
bitmap.draw(_content);
ImageCacher.SetBitmap(this.url, bitmap);
}
else
{
throw new Error("Security sandbox exception, cannot cache image.");
}
super._completeHandler(e);
}
/* Store a loaded bitmap in an internal cache */
public static function SetBitmap(name:String, bitmap:BitmapData):void
{
BITMAP_INDEX[name] = bitmap;
}
/* Return a loaded bitmap from the internal cache */
public static function GetBitmap(name:String):BitmapData
{
return BITMAP_INDEX[name];
}
}
}