First time here? First time here? Newsletter Signup Newsletter
Search tutorials
Author: Nuno Mira | Website: http://www.nunomira.com/


In Flash you build a simple layout with an image, a button and text field.

The image resides inside a MovieClip image_mc. In order to have a different image generated each time, there's a text field (text_txt) inside image_mc where different text can appear each time: The current date coming from the user's computer is being used.
The button submit_btn will process the image and send it to the PHP script. The text field status_txt will provide information about what's going on.

Place Base64.as and as3corelib.swc in the same folder as the FLA.
Add the SWC file to your FLA:

File -> Publish Settings

  • Flash tab
  • Settings
  • Library path tab
  • + button
  • ./as3corelib.swc

swc file

Now you can use of the JPGEncoder Class.

The Document Class Main.as contains the following code:

	import com.adobe.images.JPGEncoder;
	import flash.display.BitmapData;
	import flash.display.MovieClip;
	import flash.display.SimpleButton;
	import flash.display.Sprite;
	import flash.events.Event;
	import flash.events.IOErrorEvent;
	import flash.events.MouseEvent;
	import flash.net.URLLoader;
	import flash.net.URLRequest;
	import flash.net.URLRequestMethod;
	import flash.net.URLVariables;
	import flash.text.TextField;
	import flash.utils.ByteArray;

	public class Main extends Sprite 
		public var image_mc:MovieClip;
		public var submit_btn:SimpleButton;
		public var status_txt:TextField;
		private var text_txt:TextField;

		public function Main()
			// show the current time in the image's text field
			text_txt = image_mc.text_txt;			
			addEventListener(Event.ENTER_FRAME, showTime);
			submit_btn.addEventListener(MouseEvent.CLICK, submit);
		 * when you click the submit button
		 * get the image's ByteArray data
		 * send the variables to the PHP script
		 * @param	e
		private function submit(e:MouseEvent):void 
			var byteArray:ByteArray = getImageByteArray();			
			// send the variables to the PHP script
			var urlRequest:URLRequest = new URLRequest("script.php");

			urlRequest.method = URLRequestMethod.POST;			
			var variables:URLVariables = new URLVariables();
			variables.img = Base64.encode(byteArray); // the encoded ByteArray
			variables.filename = "image-" + new Date().getTime() + ".jpg"; // the name of the image
			urlRequest.data = variables;			
			var loader:URLLoader = new URLLoader();
			loader.addEventListener(Event.COMPLETE, loadComplete);			
			loader.addEventListener(IOErrorEvent.IO_ERROR, loadError);
			status_txt.text = "Sending image...";
		 * if the request was successful
		 * @param	e
		private function loadComplete(e:Event):void 
			var loader:URLLoader = URLLoader(e.currentTarget);
			status_txt.text = loader.data;
		 * if there was an error
		 * @param	e
		private function loadError(e:IOErrorEvent):void 
			status_txt.text = "Error saving image.";
		 * get the BitmapData from image_mc,
		 * get the bytearray to send to the server
		private function getImageByteArray():ByteArray
			// get the BitmapData from image_mc
			var bmd:BitmapData = new BitmapData (image_mc.width, image_mc.height);

			// convert to ByteArray
			var jpg:JPGEncoder = new JPGEncoder(85); // compression set to 85		
			var byteArray:ByteArray = jpg.encode(bmd);
			return byteArray;			
		 * show the current time in the image
		private function showTime(e:Event):void
			var myDate:Date = new Date();
			// get the seconds, minutes and hours
			var seconds:uint = myDate.getSeconds();
			var minutes:uint = myDate.getMinutes();
			var hours:uint = myDate.getHours();
			// get the year, month and day
			var year:uint = myDate.getFullYear();
			var month:uint = myDate.getMonth() + 1;
			var day:uint = myDate.getDate();
			// add leading zeros to all that may require for a better looking result
			var seconds_s:String = seconds <10 ? "0" + seconds : seconds.toString();
			var minutes_s:String = minutes <10 ? "0" + minutes : minutes.toString();
			var hours_s:String = hours <10 ? "0" + hours : hours.toString();
			var year_s:String = year.toString();
			var month_s:String = month <10 ? "0" + month : month.toString();
			var day_s:String = day <10 ? "0" + day : day.toString();
			// concatenate the values and show them in the text field
			text_txt.text = year_s + "/" + month_s + "/" + day_s;
			text_txt.appendText(" ");
			text_txt.appendText(hours_s + ":" + minutes_s + ":" + seconds_s);			

When the submit button is clicked, you get the BitmapData from the image and convert it to ByteArray. This is done in the getImageByteArray() function.
The exact dimensions of the image (which is the dimensions of image_mc) is used. The conversion from BitmaData to ByteArray is done by the JPGEncoder Class available in the AS3CoreLib package.

The data is sent to the PHP Script using the URLLoader Class via POST (which is what the PHP script is expecting).
When the request is completed the response is displayed in the status text field.

For testing purposes, along with the img variable, the filename variable is also sent. Possibly, you'll want to generate the filename on the PHP's side. In a real world example you could be sending the user's name, email, Facebook ID...
The img variable is the Base64 encoded ByteArray. It is encoded so that it can be sent using the URLLoader Class along with other variables. It will be decoded by PHP.


In order to play safe a relative URL is used. If you want to test directly from the Flash IDE, you can use an absolute one such as:

request.url = "http://localhost/flashkit/image/script.php";

When you go online, if you do need an absolute URL don't forget to add the Cross Domain Policy file to the server where the PHP script is.

Screenshot in Flash:

What you've done is taking a screenshot that will be sent to a PHP script which will create the JPG file. Obviously the BitmapData can be used in Flash to create a Bitmap that can be added to the display list:

// get the BitmapData from image_mc
var bmd:BitmapData = new BitmapData (image_mc.width, image_mc.height);

// create a Bitmap object, add the BitmapData and show it
var bm:Bitmap = new Bitmap(bmd);
bm.x = 400;

This code is available in MainDuplication.as.

Another use for the ByteArray that can be converted from the BitmapData is downloading the image directly from Flash using the FileReference Class:

var byteArray:ByteArray = getImageByteArray();

var fr:FileReference = new FileReference();
fr.save(byteArray, "image.jpg");

This requires Flash Player 10 as save() wasn't available before.

» Level Intermediate

Added: 2011-03-31
Rating: 2.75 Votes: 4
» Author
Nuno Mira has been a Flash Developer for 9 years. He loves teaching, and learning. When he isn't coding he may be surfing or snowboarding.
» Download
Download the files used in this tutorial.
» Forums
More help? Search our boards for quick answers!
Featured Flash FLA
» Author: Inocreato
» Title: RaiseTheBlocks
» Description: Raise all the blocks to win the game
Featured Sound Loops
Image for equalize

Audio Player

» Author: TomCat Carty
» Title: The Wood
» Description: Just a little game ending or it can maybe be looped. Recorders with music box and percussion to give the feel of well, I don't know, the woods? Free to use, just credit me. thank you
Latest Font
» Author: Fábio FAFERS
» Description: I created this font for free use. Everyone can apply it in personal or business texts. Its free, but I want to be communicated in case of business use. Donations are accepted to keep the project of free fonts alive! Thank you all
Featured Sound Fx
Image for equalize

Audio Player

» Author: Davisigner
» Description: Hmm... what to say about this one? It's reminiscent of the closing notes of the opening music from the Three Stooges done in a church organ style with a closing cymbal crash. I'll give this one away gratis, but feel free to check out my free loops and potential upcoming license-mandated ones over in the respective part of Flashkit.