package { import flash.display.Bitmap; import flash.display.BitmapData; import flash.display.DisplayObject; import flash.display.Loader; import flash.display.Sprite; import flash.events.Event; import flash.events.IOErrorEvent; import flash.events.SecurityErrorEvent; import flash.net.URLRequest; import flash.system.LoaderContext; public class Image extends Sprite { private var _loader:Loader; private var _width:Number = 0; private var _height:Number = 0; // Constructor usage: setting w/h to 0 will have the image take on its nominal dimensions (found out at event.INIT time) // Putting values greater than 0/0 will actually force the image to those dimensions on load. public function Image(w:Number, h:Number) { super(); _width = w; _height = h; } public function load(url:String) : void { this._loader = new Loader(); this._loader.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR, _bubble); this._loader.contentLoaderInfo.addEventListener(Event.INIT, _bubble); addEventListener(SecurityErrorEvent.SECURITY_ERROR, _bubble); this._loader.load(new URLRequest(url), new LoaderContext(true)); } private function _bubble(event:Event) : void { try { var bmpData:BitmapData = new BitmapData(this._loader.width, this._loader.height,true,0xffffff); bmpData.draw(this._loader.content); var bmp:Bitmap = new Bitmap(bmpData,"auto",true); this.addChild(bmp); } catch (exc:Error) { // If there's an error just return a black square rather than hold anything up. with(graphics) { beginFill(0x000000); drawRect(0,0,_width,_height); endFill(); } } if(event.type==Event.INIT) { if(_width>0) this.width = _width; else this._width = this._loader.width; if(_height>0) this.height = _height; else this._height = this._loader.height; } this.dispatchEvent(event); } // A reference to the original asset in case you want to access its width and height or other stuff public function get content () : DisplayObject { return this._loader.content; } } }