Image cache in flex

Voici une petite classe très utile, elle étend la classe Image du framework Flex et permet de mettre en cache automatiquement le contenu (BitmapData) de l’image chargée. Cette classe se veut très simple et compréhensible, libre à vous de la modifier pour votre projet!

Here a small very usefull Action Script class extending the Image Class of the Flex framework. This class allows to cache automatically the loaded content (BitmapData) from an URL. This class aims to be just simple and easily understable, so, feel free to do so!

package com.ebuildy.components
{
	import flash.display.Bitmap;
	import flash.events.Event;
	import flash.system.ApplicationDomain;
	import flash.system.LoaderContext;
	import flash.system.Security;
	import flash.system.SecurityDomain;
	import flash.utils.Dictionary;

	import mx.controls.Image;

	public class EbImage extends Image
	{
		static private var imageCache:Dictionary = new Dictionary(true);

		public function AffinoImage()
		{
			super();

			// Maybe usefull, was necessary for the first Flash 10.1 Beta (thanks Adobe ;-(
			if (Security.sandboxType != Security.LOCAL_TRUSTED)
			{
				var ctx:LoaderContext = new LoaderContext();

				ctx.checkPolicyFile = true;
				ctx.applicationDomain = ApplicationDomain.currentDomain;
				ctx.securityDomain = SecurityDomain.currentDomain;

				this.loaderContext = ctx;
			}			

			this.addEventListener(Event.COMPLETE, onImageComplete);
		}

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

		    if (!imageCache.hasOwnProperty(image.source))
		    {
		        imageCache[this.source] = Bitmap(this.content).bitmapData;
		    }
		} 

		override public function set source(value:Object):void
		{
			if (imageCache.hasOwnProperty(value))
			{
			    super.source = new Bitmap(imageCache[value],'auto',true);
			}
			else
			{
			    super.source = value;
			}
		}
	}
}

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>