RSS

How to Load External Images in Actionscript 3.0

This entry was posted on Mar 11 2009

loadingimage

Using the flash.display.Loader class in AS3, you can load in external image files to display in flash. The loader class supports loading in JPG, SWF, PNG, or GIF file types. The Loader class sounds more like a loading manager that watches load progress, rather than a display object. Fact is, the Loader is treated as a DisplayObject, so when it’s ready you just add it to the stage. Pretty simple, so let’s get started!

First, you will need to create an instance of the loader class and add a couple event listeners to it. One to watch load progress, and one to watch for when the loading is complete.

1
2
3
var myLoader:Loader = new Loader();
myLoader.contentLoaderInfo.addEventListener(ProgressEvent.PROGRESS, onLoaderProgress);
myLoader.contentLoaderInfo.addEventListener(Event.COMPLETE, onLoaderComplete);

You’ll notice that I’m not adding the event listener to the loader instance (myLoader), but instead adding them to a property of myLoader called contentLoaderInfo. The Loader class has a special property that controls all the loading events. This property is an instance of the LoaderInfo class, so we will listen to it for events, rather than our Loader instance.

Next, we will call the Loader.load() method to initiate the loading sequence. You will need to create a new variable that will be an instance of the URLRequest class. This new variable will be passed to the load() method.

1
2
3
4
5
6
var myLoader:Loader = new Loader();
myLoader.contentLoaderInfo.addEventListener(ProgressEvent.PROGRESS, onProgressStatus);
myLoader.contentLoaderInfo.addEventListener(Event.COMPLETE, onLoaderReady);

var fileRequest:URLRequest = new URLRequest("myImage.jpg");
myLoader.load(fileRequest);

Ok, so that’s pretty much it. All that is left is to create our callback methods for each of our eventListeners. Our final code should look like this:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
var myLoader:Loader = new Loader();
myLoader.contentLoaderInfo.addEventListener(ProgressEvent.PROGRESS, onProgressStatus);
myLoader.contentLoaderInfo.addEventListener(Event.COMPLETE, onLoaderReady);

var fileRequest:URLRequest = new URLRequest("myImage.jpg");
myLoader.load(fileRequest);

public function onProgressStatus(e:ProgressEvent) {   
      // this is where progress will be monitored     
      trace(e.bytesLoaded, e.bytesTotal); 
}

public function onLoaderReady(e:Event) {     
      // the image is now loaded, so let's add it to the display tree!     
      addChild(myLoader);
}


43 Responses to “How to Load External Images in Actionscript 3.0”

  1. Thanks. Don’t take this down yet! :)


  2. I don’t plan on taking it down anytime soon :)


  3. I am wondering this, as i sit here working on this.

    what if i wanted to use xml and?or local connection to load these images? to make them more dynamic.

    how could we add that functionality?


  4. Chad,
    This tutorial shows how to load images using the Loader class. The matter of how you get the URL for the image(s) to load is up to you. In the example above I have the URL for the image hard coded. You could use XML or other methods to obtain the URL string for the image to load.

    You can learn how to load XML here:
    http://blog.728media.com/2008/06/23/loadingand-parsing-xml-in-actionscript-3-part-1/

    Also, here are a few great tutorials on loading/parsing XML:
    http://www.gotoandlearn.com/play?id=64
    http://www.gotoandlearn.com/play?id=65


  5. Seems like a mistake in the line –

    var fileRequest:URLRequest = new URLRequest(“myImage.jpg”);

    URLRequest needs a URL format, so even a local file needs to be

    file:///User/username/path/myImage.jpg


  6. ibarra,

    That is not correct. If no directory is provided, it will determine and start in the root folder for the file. In the case of the Flash IDE, this would be the swf publish directory. In the case of the web browser and an html file that has your swf embedded, it will be the html directory.

    For this reason of the double standard, I either only test through Flex Builder and a web browser, or I put a check for flash.system.Capabilities.playerType and add the appropriate string to the front of it.

    Hope that makes sense.

    Pertaining to the article:
    I was also going to suggest that if you need to load more than one image, I prefer to store the images in some sort of array at the time each image gets loaded in. If you add directly to the stage without storing a reference anywhere else, you’ll be forced to use getChildAt(in) every time you need to access your image again. For multiple images, arrays can be helpful for looping through them in a slideshow style manner.


  7. In your onLoaderReady function, is there a way to get the myLoader object back out of the argument e? For my purposes, I’d prefer to set up and run the loader object within a function, and not have to refer to another object that is outside the function’s scope…

    Thanks for posting this and keeping this up… I’m just getting around to learning AS 3 now, and I’m finding this blog very helpful.


  8. Greg,
    Yup, you can get the loader object by calling e.target. The LoaderInfo object that fires the event passes the loader instance as the target.


  9. Just noticed a bit of a typo. In the first set of code, the callback function for contentLoaderInfo PROGRESS event is “onLoaderProgress”, but in the second and third code blocks, you’ve named this function, “onProgressStatus”


  10. ok, the second callback function also changes names. It’s first called, “onLoaderComplete” and later named, “onLoaderReady”


  11. I was not able to get this working.. I opened a blank AS3 fla and added the code put my image in the same directory with the fla and swf and nothing happens. I also seem to be getting a compile error messsage saying that :

    1114: The public attribute can only be used inside a package.

    public function onLoaderReady(e:Event) {


  12. update to my last post after removing the “public” declaration it worked.


  13. Wonderful!

    I am find to it very long time.

    Working perfect, thank again..


  14. hi, thanks for sharing this article. I was searching for this solution and helped me this exactly what i wanted….


  15. // sorry… bad english

    Hi, maybe U can help me…
    I’m trying for day to solve a problem about loading external files.
    I had made some function, pretty much like yours to load my images, the problem is that evetualy I need to load again the same image on other position.
    send the code above:

    var url:Array = [];
    var loader:Array = [];
    var target:String; // can be “target1″, “target2″, “target3″ or “target4″

    for(var nn:uint=1; nn<=99; nn++){
    //setting URLs
    url[nn] = new URLRequest("r" + nn + ".swf");

    //creating loaders to each image
    loader[nn] = new Loader();

    //setting image into loaders
    loader[nn].load(url[nn]);
    }

    //——— declaring functions —————————- ———————————-//
    function loaderComplete(e:Event):void{
    trace("carregamento completo", e.target.width, "px de largura");
    }

    // Here we set value the image, collum and line number So we can set pre-set positions in the target
    function MarcaSorteada(bolaSorteada:uint, C, L, target):void{
    //adding every loaders on the right movieClip on stage
    target.addChild(loader[bolaSorteada]);

    //adding listeners for when loading is completed
    loader[bolaSorteada].contentLoaderInfo.addEventListener(Event.COMPLETE, loaderComplete);

    // ————————————————————————————-/
    // Setting position on target /
    // ————————————————————————————-/
    //coluna 0
    if(C==0 && L==0) { loader[bolaSorteada].x = 0; loader[bolaSorteada].y = 0; }
    else if(C==0 && L==1) { loader[bolaSorteada].x = 0; loader[bolaSorteada].y = altura; }
    else if(C==0 && L==2) { loader[bolaSorteada].x = 0; loader[bolaSorteada].y = altura * 2; }

    //coluna 1
    else if(C==1 && L==0) { loader[bolaSorteada].x = largura; loader[bolaSorteada].y = 0; }
    else if(C==1 && L==1) { loader[bolaSorteada].x = largura; loader[bolaSorteada].y = altura; }
    else if(C==1 && L==2) { loader[bolaSorteada].x = largura; loader[bolaSorteada].y = altura * 2; }

    //coluna 2
    else if(C==2 && L==0) { loader[bolaSorteada].x = largura * 2; loader[bolaSorteada].y = 0; }
    else if(C==2 && L==1) { loader[bolaSorteada].x = largura * 2; loader[bolaSorteada].y = altura; }
    else if(C==2 && L==2) { loader[bolaSorteada].x = largura * 2; loader[bolaSorteada].y = altura * 2; }

    //coluna 3
    else if(C==3 && L==0) { loader[bolaSorteada].x = largura * 3; loader[bolaSorteada].y = 0; }
    else if(C==3 && L==1) { loader[bolaSorteada].x = largura * 3; loader[bolaSorteada].y = altura; }
    else if(C==3 && L==2) { loader[bolaSorteada].x = largura * 3; loader[bolaSorteada].y = altura * 2; }

    //coluna 4
    else if(C==4 && L==0) { loader[bolaSorteada].x = largura * 4; loader[bolaSorteada].y = 0; }
    else if(C==4 && L==1) { loader[bolaSorteada].x = largura * 4; loader[bolaSorteada].y = altura; }
    else if(C==4 && L==2) { loader[bolaSorteada].x = largura * 4; loader[bolaSorteada].y = altura * 2; }
    // ————————————————————————————-/
    // ————————————————————————————-/
    }

    // calling function on target 1
    MarcaSorteada(1, 0, 0, target1);
    MarcaSorteada(2, 0, 1, target1);
    MarcaSorteada(3, 0, 2, target1);
    MarcaSorteada(4, 1, 0, target1);
    MarcaSorteada(5, 1, 1, target1);
    MarcaSorteada(6, 1, 2, target1);
    MarcaSorteada(7, 2, 0, target1);
    MarcaSorteada(8, 2, 1, target1);
    MarcaSorteada(9, 2, 2, target1);
    MarcaSorteada(10, 3, 0, target1);
    MarcaSorteada(11, 3, 1, target1);
    MarcaSorteada(12, 3, 2, target1);
    MarcaSorteada(13, 4, 0, target1);
    MarcaSorteada(14, 4, 1, target1);
    MarcaSorteada(15, 4, 2, target1);

    // calling function on target 2 e 3
    MarcaSorteada(1, 0, 0, target2);
    MarcaSorteada(2, 0, 1, target2);
    MarcaSorteada(3, 0, 2, target2);
    MarcaSorteada(4, 1, 0, target2);
    MarcaSorteada(5, 1, 1, target2);
    MarcaSorteada(6, 1, 2, target2);
    MarcaSorteada(7, 2, 0, target2);
    MarcaSorteada(8, 2, 1, target2);
    MarcaSorteada(9, 2, 2, target2);
    MarcaSorteada(10, 3, 0, target3);
    MarcaSorteada(11, 3, 1, target3);
    MarcaSorteada(12, 3, 2, target3);
    MarcaSorteada(13, 4, 0, target3);
    MarcaSorteada(14, 4, 1, target3);
    MarcaSorteada(15, 4, 2, target3);

    //======================================= end of the code ================================================//

    Problem is:
    if I set to load Image "X" on target 1 AND target 2, it is only see on target 2
    if I set to load Image "X" on taget 1 AND target 2 AND target 3, it is only seem on target 3

    I think it is respositioning the images insted of creat a new one.
    Do you have any ideas how to make that work?

    regards.


  16. This is excellent — worked great.

    However, in my particular case, I had to remove the Public keyword from both methods because I was getting this error —

    “1114: The public attribute can only be used inside a package.”

    Also — it would be really nice to know how to resize the image or place it in a particular X / Y coordinate — those are the two most important image functions I’d think.

    Thanks for your code.


  17. Andrew,
    The code provided in this tutorial is to be used within a class file. Since you are putting the code on a frame, you would need to use the “public” keyword.

    In order to alter the image’s width/height or x/y position you just need to access your image’s properties as so: myMovieclip.x = 100. You can replace .x with width, height, or y in order to change any of those properties.


  18. @Andrew — Thanks, that seemed to work.

    Once again, thanks for the useful tutorial. Keep up the good work.


  19. Please tell me the font you are using for your code listings. It’s very readable, I love it!


  20. thanks alot of for ur tutorial, i want ask u, if the CHILD more than the Canvas, what can i do? i use scale formula or? thanks


  21. You can use the UILoader as well. It has built-in properties like ‘percentLoaded’ and ‘scaleContent’. Nice and easy.


  22. Thank you for this article, it was very helpful.


  23. Is there a way to code it to load the “nextImage” or the “image1*(+1).jpg” or something? Having to make individual buttons to load each image seems like a bit of a few steps backwards in terms of EFFICIENCY


  24. Nameshee,
    You would need to program additional code to handle loading images for customized playback. Your project would have a custom class that would figure out which image to load based on user feedback and use the code above to load said image.

    This link might help you out with your custom class: http://www.thetechlabs.com/tutorials/xml/create-a-as3-slideshow-with-xml/


  25. Is there a way to get the external image width height? I have a clip that needs the width to stop my image from scrolling to the right.

    var scrollSize:int = stage.stageWidth;
    var contentSize:int = bg_mc2.width;
    var outOfViewSize:int = contentSize-scrollSize;
    var divideBy:Number = scrollSize/outOfViewSize;
    var moveToPos:int;

    bg_mc2 is the place holder for my external image. Any help would be very helpful, thanks in advance.


  26. Spettie,
    You would access the width property of your Loader object that is loading the image. So if bg_mc2 is your Loader instance you would do “bg_mc2.width” to get the width of the external image. You could also try accessing the content property of the Loader object to get the actual image file dimensions by using “bg_mc2.content.width”. The content object may return different results based on the load progress of your object. I’m not sure if you can access a Loader object’s width/height properties correctly immediately after load starts or until enough metadata has been loaded.


  27. Thanks Andrew, You are right on having to wait for the metadata to be loaded. I had to get the width after the load of the image, but it does work. thanks again, you the man.


  28. Spettie,
    No problem. You could load an external XML playlist file after the flash movie loads that holds the information of what external files to load when and also pass in their respective width/height/etc properties. That way instead of trying to access those properties from the Loader object you can parse them out from the XML file before any of the files are loaded.

    Here is a quick tutorial on doing something similar to this: http://www.thetechlabs.com/tutorials/xml/create-a-as3-slideshow-with-xml/


  29. Is their a way to adjust the display order of the image.

    I want the image to be displayed between objects in my scene.

    you can see the URL here:
    http://stage.indentstudios.com/cinerama/cinerama_header_v1.html


  30. Fred,
    as2:
    You can use the swapDepths() method

    as3:
    Use the setChildIndex() method or addChildAt() method.


  31. Great tutorial! It’s proving very useful so far.


  32. This is my class with your code incorporated:

    package {
    import flash.display.MovieClip;
    import flash.display.Sprite;
    import flash.display.Loader;
    import flash.text.TextField;
    import flash.events.*;
    import flash.net.*;

    public class Content extends MovieClip {

    public var projType:TextField;
    private var imgFrame:Sprite;
    private var imgLoader:Loader;

    public function Content(txt) {

    imgFrame = new Sprite();
    imgFrame.graphics.lineStyle(1, 0x2C2F43, .3);
    imgFrame.graphics.moveTo(0, 0);
    imgFrame.graphics.lineTo(0, 150);
    imgFrame.graphics.lineTo(270, 150);
    imgFrame.graphics.lineTo(270, 0);
    imgFrame.graphics.lineTo(0, 0);
    addChild(imgFrame);

    projType = new TextField();
    projType.autoSize=”left”;
    projType.height=26;
    projType.htmlText=txt;
    projType.x=imgFrame.x;
    projType.y=imgFrame.y+imgFrame.height;
    addChild(projType);

    var imgLoader:Loader = new Loader();
    imgLoader.contentLoaderInfo.addEventListener(ProgressEvent.PROGRESS, onProgressStatus);
    imgLoader.contentLoaderInfo.addEventListener(Event.COMPLETE, onLoaderReady);

    var fileRequest:URLRequest=new URLRequest(“assets/jpg/temp03.jpg”);
    imgLoader.load(fileRequest);

    }
    public function onProgressStatus(e:ProgressEvent) {
    // this is where progress will be monitored
    trace(e.bytesLoaded, e.bytesTotal);
    }

    public function onLoaderReady(e:Event) {
    // the image is now loaded, so let’s add it to the display tree!
    addChild(imgLoader);
    }
    }
    }

    I get the following error when I run it:

    TypeError: Error #2007: Parameter child must be non-null.
    at flash.display::DisplayObjectContainer/addChild()
    at Content/onLoaderReady()

    I’m guessing I need to add the child onto an existing mc? I’m a little lost..


  33. Hi:

    First , Thanks for posting this tutorial!

    Second, what if i want to load more than one images using an array and not using xml file?
    How am i going about doing that?


  34. Sammi,
    Your array holding image urls would be hard coded. Then just run a loop through the array and load each array value using the code from the tutorial.


  35. Thanks for replying, Andrew.
    I’m able to load in the texts, but unable to load in the external images. Maybe you can help walk me through the logic? I’ve noted where I get lost. Thanks!

    package proj
    {
    import flash.events.Event;
    import flash.events.MouseEvent;
    import flash.display.MovieClip;
    import flash.display.Loader;
    import flash.net.URLRequest;
    import flash.display.Bitmap;

    public class DisplayTextsImages extends MovieClip {

    public var myArr:Array = ['Monday', 'Tuesday', 'Wednesday', 'Thursday'];

    public var imgLoader:Loader;
    public var imgRequest:URLRequest;
    public var image:Bitmap;

    public var imgHolder:MovieClip;

    public function DisplayTextsImages():void {

    for ( var i:Number = 0; i < 8; i++ )
    {
    this[ 'btn' + i ].buttonMode = true;
    this[ 'btn' + i ].id = i;
    this[ 'btn' + i ].addEventListener(MouseEvent.CLICK, onClick);
    this[ 'btn' + i ].addEventListener(MouseEvent.ROLL_OVER, onClick);
    this[ 'btn' + i ].addEventListener(MouseEvent.ROLL_OUT, onClick);
    }

    loadImg();

    }

    public function onClick (e:MouseEvent):void
    {
    if (e.type == 'rollOver') e.target.alpha = .5
    else if (e.type=='rollOut') e.target.alpha= 1
    else if (e.type=='click')
    {
    // I'm lost here
    txt.text= myArr[e.target.id];
    loadImg(e.target.id);
    }
    }

    public function loadImg():void
    {
    var imgURL:String = '_images/'; // I'm lost here

    imgLoader = new Loader();
    imgLoader.load(new URLRequest(imgURL));

    imgLoader.contentLoaderInfo.addEventListener(Event.COMPLETE, imgLoaded);
    }

    public function imgLoaded(e:Event):void
    {
    var image = new Bitmap();
    image = e.target.content;

    imgHolder = new MovieClip();
    addChild(imgHolder);
    imgHolder.x = 200;
    imgHolder.y = 30;
    imgHolder.addChild(image);
    }

    }
    }


  36. I’m more of a designer than a coder, but I’ve decided to jump into Actionscript3. Your loader works great. Of course it continues to run when I change frames and I have attempted to construct an onexitFrame listener connected to a remove.child… but I don’t yet have the feel. Can you give me a boost?


  37. Thanks, worked excelent!


  38. how to resize the image inside flash?


  39. Just a correction:

    Andrew Christiensen said:

    “Also, here are a few great tutorials on loading/parsing XML:
    http://www.gotoandlearn.com/play?id=64
    http://www.gotoandlearn.com/play?id=65

    but the tutorials have now moved to:

    http://www.gotoandlearn.com/play.php?id=64
    and
    http://www.gotoandlearn.com/play.php?id=65
    respectively


  40. Thank you much, very useful for us.


  1. 3 Trackback(s)

  2. Memory – 1 « Webanimatie+ – Jef Verschueren
  3. Externe afbeeldingen « WebAnimatie+
  4. Calling as an external swf (init function?) - OXYLUS Flash Board

Post a Comment