10-17-2008
Actionscript 3: Loading External Images
This is the best way I have found of loading images, catching any error that might come along. This can also be used for loading external swf files, just changing the Bitmap in the imageLoaded method to MovieClip
private function loadImage():void
{
var loader:Loader = new Loader();
try
{
loader.load(new URLRequest("path to image"));
}
catch(e:Error){}
loader.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR, io, false, 0, true);
loader.contentLoaderInfo.addEventListener(ProgressEvent.PROGRESS, loadProgress, false, 0, true);
loader.contentLoaderInfo.addEventListener(Event.COMPLETE, imageLoaded, false, 0, true);
}
private function loadProgress(e:ProgressEvent):void
{
var percent:String = Math.round(e.bytesLoaded / e.bytesTotal) * 100 + "% loaded";
trace(percent);
}
private function imageLoaded(e:Event):void
{
e.currentTarget.removeEventListener(IOErrorEvent.IO_ERROR, io);
e.currentTarget.removeEventListener(ProgressEvent.PROGRESS, loadProgress);
e.currentTarget.removeEventListener(Event.COMPLETE, imageLoaded);
var image:Bitmap = e.target.content as Bitmap;
addChild(image);
}
private function io(e:IOErrorEvent):void{}
Also, this may be used in the IDE (if you aren’t using classes), by removing the private from the private function.
var loader = new Loader();
loader.contentLoaderInfo.addEventListener(Event.COMPLETE, materialComplete);
loader.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR, ioErrorHandler);
loader.contentLoaderInfo.addEventListener(ProgressEvent.PROGRESS, materialProgress);
var request:URLRequest = new URLRequest(material);
try {
loader.load(request);
} catch (e) {
stat.text = “Error Loading File.”;
}
ioerrorevent does not trigger when the file is not found :S
Are you getting any other error? Your code looks correct, and I just ran it and it worked for me.
that was exactly what I was looking for and works perfect.. thanks a lot!