Skip to content

Dynamically loading images from the web in Flex 3

Dear Reader,

This weekend’s Flex project was more successful that last weeks. At least the code has survived this far without me declaring it a bust and moving on to the next project.

This week’s project involves (among other things) calling an API that returns a graphic and then displaying it on-screen. Being the Flex neophyte I am, I assumed that this was a simple call to HTTPService. Unfortunately, as I found out, that won’t work. HTTPService is designed specifically to work with APIs that return specific types of data.

What didn’t work

<mx :HTTPService id="service" 
                 url="http://calevans.com/dynamicImageDemo/index.php" 
                 contentType="application/x-www-form-urlencoded"
                 resultFormat="text"
                 result="displayImage(event)" />

Most of my API interaction using Flex has been using the HTTPService control and for APIs that return data, it’s the best choice. However, in this case my API is returning a jpg. HTTPService just ignores that. I tried all valid values for resultFormat – object, array, xml, flashvars, text, e4x – thinking that one of them would solve the problem and I could get on with building the program. Alas, no such luck, it’s just not designed to do that. Lucky for me though, I’m not the first person who has needed to do that. Flex has a control designed to help with this, the Loader control.

My Simple API

First, let’s get a sample API to play with. All we really need is a URL that return image data. Here’s my sample:

1
2
3
< ?PHP
header('Content-type: image/jpeg');
readfile('./demo.jpg');

You really can’t get much simpler than this. In most cases your API would actually manipulate the graphic but in our case, we just need something that is not specifically and image that returns image data.

What did work

The Flex project is very simple for my demo, set yourself up a Flex project and paste this in and it should run. Once you’ve got it working, let’s look at it up close.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
< ?xml version="1.0" encoding="utf-8"?>
<mx :WindowedApplication xmlns:mx="http://www.adobe.com/2006/mxml" 
	                 layout="absolute" 
	                 creationComplete="init();"  
                         horizontalScrollPolicy="off" 
                         verticalScrollPolicy="off" 
	                 height="100" 
                         width="100" 
                         visible="false" 
                         title="Dynamic Image Load Demo">
<mx :Script>
	< ![CDATA[
		protected function init():void
		{
			var loader:Loader = new Loader();
            loader.contentLoaderInfo.addEventListener(Event.COMPLETE, displayImage);		 	
			loader.load(new URLRequest('http://calevans.com/dynamicImageDemo/index.php'));
			return;			
		}
 
		protected function displayImage(event:Event):void
		{
		 	var loader:Loader = (event.target as LoaderInfo).loader;
		 	myImage.data   = loader.content;
		 	myImage.width  = loader.width;
		 	myImage.height = loader.height;
		 	this.height    = myImage.height;
		 	this.width     = myImage.width;
		 	this.visible = true;
		 	return;			
		} // protected function displayImage(event:Event):void
 
	]]>
 
 
	<mx:Image horizontalCenter="0" verticalCenter="0" id="myImage"/>
</mx:WindowedApplication>

Here’s what the finish application will look like:

Lines 1-10 are the application tag. The only thing of importance here is line 4 where fires our init() method. This is where we actually start the image loading process.

init()

The Loader control is the key to this working. Here’s a description of the control from the Flex 3 manual.

The Loader class is used to load SWF files or image (JPG, PNG, or GIF) files. Use the load() method to initiate loading. The loaded display object is added as a child of the Loader object.

This control is exactly what we need to be able to dynamically load an image. In the init() we create our Loader, we add an event listener to the loader.contentLoaderInfo. not just the Loader, and we call the load Method with our URL wrapped in a URLRequest object.

displayImage()

Once the image is loaded, our displayImage() method will fire and we finish up. Our event contains our Loader so we pull that out into it’s own variable. Then we replace our image’s data with the loader’s content. That’s really all you have to do. I adjust the size of the window to fit the new image.

Yes, it works…but why do this?

The project I’m working on has an initial dummy image. It is just a place holder until I get some input from the user. Then, once I have the input, I need to replace the image. In my case, the user input is passed to the API via an HTTP POST so I can’t just destroy the image and create a new one. I needed a solution that allowed me to dynamically change the image itself. As you can see from the demo, this solution works well for this. In my production app, since I need to submit values to the API via the POST, U create the URLRequest object in advance of the loader, build and array of parameters, tell it to POST instead of GET and then I create the loader and call load().

Until next time,
I <3 |<
=C=

[DISCLAIMER: I work with Blue Parabola, Adobe is a customer of Blue Parabola. ]

One thought on “Dynamically loading images from the web in Flex 3

Comments are closed.