AS3.0 关于用URLLoader加载外部图片

很多人都想当然的直接用URLLoader加载外部图片然后通过byteArray去转化成bitmap,其实也是可行的,但是出问题几率也会大很多。

我推荐一个比较实用的方法用URLLoader以二进制的方式加载外部图片,获得URLLoader.data的ByteArray数据,再用Loader去加载,这时Loader.content就是一个bitmap了
以下是一个例子
[code]
package {
        import flash.display.Bitmap;
    import flash.display.Loader;
        import flash.display.MovieClip;
    import flash.display.Sprite;
    import flash.events.Event;
    import flash.filters.ConvolutionFilter;
    import flash.net.URLLoader;
    import flash.net.URLRequest;
        import flash.net.URLLoaderDataFormat;
        import flash.utils.ByteArray;
   
    public class Main extends Sprite{
        private var loader:URLLoader;
        public function Main():void{
            loadImage("image.jpg");
        }
        private function loadImage(_path:String ):void{
            loader = new URLLoader;
                        loader.dataFormat=URLLoaderDataFormat.BINARY ;
            loader.addEventListener (Event.COMPLETE , onImageLoaded);
            loader.load(new URLRequest (_path));
        }
        private function onImageLoaded(e:Event):void {
                        var _ba:ByteArray = e.target.data as ByteArray;
                        var _l:Loader = new Loader;
                        _l.contentLoaderInfo.addEventListener (Event.COMPLETE, onBytesLoaded);
                        _l.loadBytes(_ba);
            //-------------------
            loader.removeEventListener (Event.COMPLETE , onImageLoaded);
            loader = null;
        }
                
                private function onBytesLoaded(e:Event):void 
                {
                        var _bitmap:Bitmap = e.target.content as Bitmap;
                        trace(_bitmap.width, _bitmap.height );
                        addChild (_bitmap );
                        //
                        e.target.loader.contentLoaderInfo.removeEventListener (Event.COMPLETE, onBytesLoaded);
                }                
    }
}
[/code]

你可能感兴趣的:(loader)