Loading a image on the fly

In flash you can load images from a remote server on-the-fly whilst the flash is running within the browser, here I am going to show how to load a image into a Image tag.

To start off you need to setup the environment to compile up the flash code into SWF file, (here is a previous tutorial where I have created the development environment for flash in creating the classic hello world)

As a side note, the image that I am loading I have taken from the openclipart website and it is off a laptop which I have made slightly smaller to load into the embed object within the HTML (web) page.

To start off, we first create a flash tag of Image (mx is the subscript as such of the flash library) with having the id of imageLoad, we can access the tag within the actual code, and then create a Button which once clicked calls a function called “loadImageIntoImageBlock” the event that is attached to the function is what happened to call this function which would be a mouse event.

	<mx:Image x="30" y="30" id="imageLoad" />
	<mx:Button label="Click here to load image" click="loadImageIntoImageBlock(event)" />

and now when the Button has been clicked we just need to call the function, which is below, the imageLoad is the ID name from the mx:Image above and then just need to alter the source to the image that is in the same place as the swf file.

private function loadImageIntoImageBlock(e:MouseEvent):void {
	imageLoad.source = 'johnny_automatic_laptop.png';
}

that is about it, here is the full source code, if you call this imageload.mxml

<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute">
	<mx:Image x="30" y="30" id="imageLoad" />
	<mx:Button label="Click here to load image" click="loadImageIntoImageBlock(event)" />
	<mx:Script>
		<![CDATA[
			private function loadImageIntoImageBlock(e:MouseEvent):void {
				imageLoad.source = 'johnny_automatic_laptop.png';
			}
		]]>
	</mx:Script>
</mx:Application>

I always place my swf files within a bin directory, so if you create a bin directory where the above imageLoad.mxml file is and then run this (once your development environment is setup e.g. the PATH variable to find the mxmlc executable file), once that is place you can compile up the code into a swf by

mxmlc imageload.mxml -output ./bin/imageload.swf

which places the imageLoad.swf into the bin directory that was created.

Here is the web page code that will load the imageLoad.swf into a web page, if you save this as loadingimage.html within the same bin directory as above with the ‘johnny_automatic_laptop.png’ image within the same bin directory you can then open up the html page within your favourite web browser (Firefox) and then click on the button and it will load in the image. hey presto

<html>
<body>
<embed src="imageload.swf" width="560" height="560">
</body>
</html>