AS3-来自URL的缓存图像
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了AS3-来自URL的缓存图像相关的知识,希望对你有一定的参考价值。
Retrieve remote image from an URL and store it locally.Use this class for managing offline mode.
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; } } }
以上是关于AS3-来自URL的缓存图像的主要内容,如果未能解决你的问题,请参考以下文章