Revision: 54009
Initial Code
Initial URL
Initial Description
Initial Title
Initial Tags
Initial Language
at December 6, 2011 09:50 by spawnrider
Initial Code
package components { import com.adobe.crypto.MD5; import flash.events.Event; import flash.filesystem.File; import flash.filesystem.FileMode; import flash.filesystem.FileStream; import flash.net.URLLoader; import flash.net.URLLoaderDataFormat; import flash.net.URLRequest; import spark.components.Image; public class CachedImage extends Image { private var _imageIdentifier:String = ""; private var urlLoader:URLLoader = new URLLoader(); private var _fromCache:Boolean = false; public function CachedImage() { super(); } public function get fromCache():Boolean { return _fromCache; } public function set fromCache(value:Boolean):void { _fromCache = value; } public function get imageIdentifier():String { return _imageIdentifier; } public function set imageIdentifier(value:String):void { _imageIdentifier = value; } override public function get source():Object { return super.source; } override public function set source(value:Object):void { if(!_fromCache) { if(value is Class){ // do nothing } else if(value is String || value is Object){ //Load cached image _imageIdentifier = MD5.hash(String(value)); // Cache the image var cacheFile:File= File.applicationStorageDirectory.resolvePath(_imageIdentifier); if (cacheFile.exists) { trace("ImageCache - Load Cached image from : "+cacheFile.url); _fromCache = true; super.source = cacheFile.url; return; } else { trace("ImageCache - Cached image not found, create it"); urlLoader.dataFormat = URLLoaderDataFormat.BINARY; urlLoader.load(new URLRequest(String(value))); urlLoader.addEventListener(Event.COMPLETE,imageLoaded); return; } } } trace("ImageCache - Load image from : "+value); super.source = value; } // when remote image is loaded, cache it ! protected function imageLoaded(event:Event):void { var tilefile:File = File.applicationStorageDirectory.resolvePath(_imageIdentifier); if (tilefile.exists) { trace("ImageCache - Already exist, recreate it"); tilefile.deleteFile(); } trace("ImageCache - Cache image"); var fileStream:FileStream = new FileStream(); fileStream.open(tilefile, FileMode.WRITE); fileStream.writeBytes(urlLoader.data); fileStream.close(); _fromCache = true; super.source = tilefile.url; } } }
Initial URL
Initial Description
Retrieve remote image from an URL and store it locally. Use this class for managing offline mode.
Initial Title
AS3 - Cached image from URL
Initial Tags
script, cache
Initial Language
ActionScript 3