Visit our archive

In Part 1 of this tutorial, we showed you how to use the JPGEncoder and PNGEncoder classes to save files to your server for user sharing. What we didn’t show you was how to generate an image for the user to save. The process is almost identical, but there are a couple of key differences that we are going to point out in this tutorial.
* we recommend reading through part 1 for some background on the code that we are going to show in this post.

We are going to keep this simple, since most of the necessary information was listed in Part 1. What we have done, is created two new functions in the SaveImage class that we built in Part 1, and added a little bit of PHP code to the service file.

Here are the new functions in the SaveImage as3 class, we will show the code and then explain what happened after.

public function saveJPGToUser(image:BitmapData, filename:String, quality:Number = 90):void

	var imageFile:ByteArray = (new JPGEncoder(quality)).encode(image);
	var imageFileName:String = filename + ".jpg";

	var url:String = SERVICE_PATH + "?type=jpeg&name=" + imageFileName;

	var req:URLRequest = new URLRequest(url);
	req.requestHeaders =  [new URLRequestHeader("Content-type", "application/octet-stream")];
	req.method = URLRequestMethod.POST; = imageFile;

	navigateToURL(req, "_blank");


public function savePNGToUser(image:BitmapData, filename:String):void

	var imageFile:ByteArray = (PNGEncoder.encode(image));
	var imageFileName:String = filename + ".png";

	var url:String = SERVICE_PATH + "?type=png&name=" + imageFileName;

	var req:URLRequest = new URLRequest(url);
	req.requestHeaders =  new Array(new URLRequestHeader("Content-type", "application/octet-stream"));
	req.contentType = "application/octet-stream";
	req.method = URLRequestMethod.POST; = imageFile;

	navigateToURL(req, "_blank")


As you may notice, we are encoding both the PNG and JPG files in the same way as we did in part 1, using the JPGEncoder and PNGEncoders respectively. We then go on to create very similar URLRequests, with one big exception.. the URLRequestHeader. In part 1 we used image/jpeg and image/png as the request headers so that the PHP would treat this as an image, we are now using application/octet-stream which allows us to send the same data to PHP but have it interpreted as an attachment for download.

The other big change is that we are no longer using a URLLoader to pass the data to the service, we are using navigateToURL. So we are essentially linking to the file. The interesting part in this is that we are linking to the file before it is created, that is what the update in the PHP is going to take care of for us.

Our PHP script is now looking for a new GET variable that we slipped into the as3 functions, called type. This type should be either ‘png’ or ‘jpeg’ so that the PHP can know what type of image it is attaching. Here is the updated code for the PHP script that we are now linking to:

// make sure the file is safe to save on the server
function sanitize($string, $force_lowercase = true, $anal = false) {
    $strip = array("~", "`", "!", "@", "#", "$", "%", "^", "&", "*", "(", ")", "_", "=", "+", "[", "{", "]",
                   "}", "\", "|", ";", ":", """, "'", "‘", "’", "“", "”", "–", "—",
                   "—", "–", ",", "<", ".", ">", "/", "?");
    $clean = trim(str_replace($strip, "", strip_tags($string)));
    $clean = preg_replace('/s+/', "-", $clean);
    $clean = ($anal) ? preg_replace("/[^a-zA-Z0-9]/", "", $clean) : $clean ;
    return ($force_lowercase) ?
        (function_exists('mb_strtolower')) ?
            mb_strtolower($clean, 'UTF-8') :
            strtolower($clean) :

if ( isset ( $GLOBALS["HTTP_RAW_POST_DATA"] ) && isset( $_GET['name'] ) ) {

	// get a timestamp from the server
	$uniqueStamp = date(U);

	// prepend the timestamp to the filename and sanitize it
	$fileName = sanitize($uniqueStamp . $_GET['name']);

	// get the binary stream

	if ( isset ( $_GET['type'] ) ) {

		// add headers for download dialog-box
		header('Content-Type: image/' . $_GET['type']);
		header("Content-Disposition: attachment; filename=" . $_GET['name']);
		echo $im;

	} else {

		//write it
		$fp = fopen($fileName, 'wb');
		fwrite($fp, $im);

		$arr = array ( "success" => "true", "file" => $fileName );
		echo json_encode($arr);

}  else {

	$arr = array ( "success" => "false", "error" => "Header data set incorrectly" );
	echo json_encode($arr);

As you can see, the only thing that we are really doing is setting the Content-Type to be the image that you specified, and we are setting a Content-Disposition so that the browser recognizes the page as an attachment. Finally, we are printing out the contents of the attachment (the image ByteArray).

Now when you call the saveJPGToUser or savePNGToUser from the SaveImage class, it will generate the image, pop open a new window, and display a browser download dialog-box where the user can now save the image to their system.

Feel free to download the class file by clicking on this link..

share save 171 16 Saving Images from Flash to PHP   Part 2
  • Name (Required)

  • Email (Required, but not published)

  • Url (Optional)

  • Comment (Required)


Current month ye@r day *