Loading external images in AS3

13 April 2007

I thought I would post this as all the tutorials I found about loading external images in AS3 were either not working or very confusing. So here is a quick way of loading external images. For the sake of this example I will show only the methods needed in a class. First, we need to create a new Loader object. We then need to add an event listener to check when the image has loaded completely and add it to the display list. So lets start with creating the new object and adding the event.

public function loadImage():void
{
    var loader:Loader = new Loader;
    loader.contentLoaderInfo.addEventListener(Event.COMPLETE, imageLoaded);
    loader.load(new URLRequest("assets/sample.jpg"));
}

Next we need to create a method to deal with the event that will be dispatched when the image has completely loaded. This method takes one parameter which is an object of the Event class. It contains the data that we want, in order to display this image on the stage. Remember drawing items on the stage is a 2 part process in AS3, create and add to stage.

private function imageLoaded(event:Event):void
{
    var image:Bitmap = new Bitmap(event.target.content.bitmapData);
    addChild(image);
}

I hope this helps some of you out there who have been in the process of migrating from AS2 to AS3, or just been playing around. Remember to import the necessary classes to deal with the event, loader and bitmap objects we used. Selah.

03 October 2011 | Talvinen

I'm beginner in AS3, and your example was very helpful for me. Thanks!

12 April 2011 | Cjous

Duuuuuude! Super clear and simple! Thanks a million! I was getting so frustrated over not finding the answer to this very problem! Thanks again!

29 June 2009 | worked

Hey there- Thanks for the tip. Question. Once the image is loaded, how do I change the registration point (with actionscript)? I know how to manipulate a reg point on items found in the library. Any help would be appreciated. Thanks!

28 May 2009 | Sven

And how do you use this code in a repeating image gallery with crossfading images? I somehow need to get the image over and over again, but without calling the Loader a second time, as I asume the image is cached.

23 March 2009 | flacoloco

Thanks a lot. I loaded the image properly but I didn't use the Bitmap so I couldn't set the size of the image. Great code!

19 March 2009 | Insignia

I thought it was going to be a long night but you proved me wrong. new UrlRequest is the code I needed in order to load images locally from my machine as opposed to an loading imagines from a url.

05 January 2009 | luke

yeah good code. waaaay simpler than the others out there.

Incorrect please try again