Loading an external .jpg, .png, or .gif bitmap image file in ActionScript 3.0

In AS3, loading external images dynamically is done slightly differently than in ActionScript 2. Whereas in AS2, we could just use the loadMovie() method of the MovieClip class, this is no longer the case.

(Download the files for this tutorial.
You will also need: Flash CS3. Download Trial or Buy Now.)

Instead we have to use the Loader class, as well as the URLRequest class. This actually gives us more flexibility when loading external images, because of the various events of the Loader object that we can create event listeners for.

Let’s say that we a .swf file called “main.swf”, a document class file called “Main.as”, and a .jpg file called “thePic.jpg” in a directory called “images/”. (If you are not yet familar with the document class, please see this tutorial).

Our directory structure would look like the following (click to expand):

picture-7.png

In order to load the .jpg into our file, we first need to import the correct classes into our scope. We will require the URLRequest and Loader classes, and also, we’ll go ahead and import the “events” package, since it is often good practice to have all of the events handy.


The Code

Here is our code for the Main.as file so far:


package {
	import flash.display.MovieClip;
	import flash.display.Loader;
        import flash.events.*;
	import flash.net.URLRequest;

Next, we’ll go ahead and make our constructor, a function called Main(). Inside our constructor we will create:

  1. A Loader object, called imageLoader;
  2. A URLRequest object, called imageRequest.

We will pass the path to our bitmap image (which should be a .gif, .jpg, or .png file), to the URLRequest() constructor. In our case it will be a .jpg.

package {

     import flash.display.MovieClip;
     import flash.display.Loader;
     import flash.events.*;
     import flash.net.URLRequest;

	public class Main extends MovieClip {

		public function Main() {

		var imageLoader:Loader = new Loader();

		var theURL:String = "images/thePic.jpg";

		var imageRequest = new URLRequest(theURL);

Next, we will add the all-important event listener. As you should now be aware, interactivity is all about events (so you should get to know your event listener syntax :) ). Please note here, that we are not adding the event listener directly to the Loader object, we are passing it to one of its properties, its contentLoaderInfo object. For more about the contentLoaderInfo class, see the Adobe docs here. This object will trigger an event called “COMPLETE” when everything is loaded, so this is what we will listen for. To this event we assign the listener onComplete(), to be defined later (see below).

After the event listener is set, we then call the load() method of the Loader() object that we have instantiated as imageLoader.

Lastly, placing the image on stage is handled by our (nested) function called onComplete(). It does the work of adding our newly loaded DisplayObject instance (in this case the content property of a Loader object) to the display list using addChild(). The complete constructor function is below:


public function Main() {

     var imageLoader:Loader = new Loader();
     var theURL:String = "images/thePic.jpg";
     var imageRequest = new URLRequest(theURL);

     imageLoader.contentLoaderInfo.addEventListener(Event.COMPLETE, onComplete);

     imageLoader.load(imageRequest);

     function onComplete(evt:Event) {

          addChild(imageLoader.content);

     }

}

Notice the line:

addChild(imageLoader.content);

The content property of the Loader object is used here because it actually contains our image. If we want to manipulate it as a Bitmap however, we will have to cast it to the correct data type (not covered in this tutorial).

Don’t Forget to Unload the Image When You are Done With It

The title of this section says it all. You should use the removeChild() method of the DisplayObjectContainer that the object belongs to (in this case our main timeline), as well as the Loader.unload() method to remove all references to the loaded image. (Unless you want to keep the bitmap in memory of course). Once there are no remaining references, our good friend the garbage collector will remove the bitmap from memory.

And that concludes this tutorial. I hope you enjoyed it. Ciao and happy ActionScripting!

Tags: , , , , , ,

Jay Harley is the CEO and web architect of Heaven Interactive. As a technologist, Jay specializes in creating business productivity software and offering clients high-level media consulting services. Before founding Heaven Interactive, Jay led a double life as a web consultant and MFA New Media instructor at the Academy of Art University in San Francisco. At AAU, he enthusiastically developed several courses in web application design and scripting, and enjoyed daily interaction with design students, offering guidance, support, and camaraderie as a media professional. Jay is now squarely focused on providing Web 3.0 solutions to businesses in the form of collaboration and presentation software, by utilizing the power of the "Web as a Platform."



7 Comments so far

  1. [...] Read the tutorial and download source files No Comments Leave a Commenttrackback addressThere was an error with your comment, please try again. name (required)email (will not be published) (required)url [...]

  2. michael on May 7th, 2008

    this is very nice u have done it without xml.
    but i want to add more than one image,i want to add few images one after one and display them in fading effect.

    plz tell me how………………….

  3. Andrian on June 1st, 2008

    I have a similar set up it works with jpegs and pngs but it give me an “Unknown file format loaded” error for bitmaps?

    Did anybody try this with bitmaps?

  4. BiNHs on July 5th, 2008

    And what happen if I want to threat that image as a BitMapData?

    As you said: “If we want to manipulate it as a Bitmap however, we will have to cast it to the correct data type (not covered in this tutorial). ”

    How can I do this?

  5. Bushwa on August 11th, 2008

    I’m trying to load the image and place it in the background, but I have yet to grasp not using levels in AS3.
    Any suggestions?
    Thanks

  6. Jay Harley on August 18th, 2008

    Well ‘levels’ are not really applicable to AS3 per se. It is really based around the Display List system…. You can control the layers of your images by ordering their place in the display list.

    Display objects (such as your background) can be higher or lower in the display list. You could put all of your objects ‘on top of’, or ‘higher’ in the dislay list.

    I would read the Adobe tutorials to get some background on this.

    Jay

  7. pligg.com on July 10th, 2009

    Loading an external .jpg, .png, or .gif bitmap image file in ActionScript 3.0…

    This tutorial will show you how to load external images using AS3 in Flash and Flex, as well as to handle events such as the completion of the image loading for true interactivity….

Leave a Reply

You must be logged in to post a comment.