UPDATE: Flash Player 10 has a save method that can be used instead of calling PHP. The version in this post will work with both version 9 and 10. You can find an example of the updated method here.
Problem:
The added security in Flash player 10 requires user interaction prior to download. This can be a pain if your server processes the image and returns a URL forcing the user to click AGAIN to download it. Who wants to click twice to download an image?
Solution:
Cut out the middle man. Don’t save the image onto the server, just use PHP to post it back to Flash. In one line of PHP code you can seamlessly download the image from Flash and with only one click from the user! No white windows flashing, no files written to your server and no headaches for the user.
Try it out!
(draw a picture above than click on the download link!)
Full source code can be found here.
The ActionScript side of things is less than 50 lines of code:
package com.cb.utils.image { import com.adobe.images.JPGEncoder; import com.hurlant.util.Base64; import flash.display.BitmapData; import flash.display.Sprite; import flash.net.FileReference; import flash.net.URLRequest; import flash.net.URLRequestMethod; import flash.net.URLVariables; import flash.utils.ByteArray; import mx.utils.Base64Encoder; public class ImageDownloader { private var DOWNLOAD_URL:String = "http://www.blackcj.com/blog/wp-content/swfs/RoundTripImaging/php/process.php"; public function ImageDownloader(){} public function download(canvas:Sprite):void { var bitmapData:BitmapData = new BitmapData(canvas.width, canvas.height); bitmapData.draw(canvas); var byteArray:ByteArray; var jpgEncoder:JPGEncoder = new JPGEncoder(85); byteArray = jpgEncoder.encode(bitmapData); var b64e:Base64Encoder = new Base64Encoder(); var byteArrayAsString:String = Base64.encodeByteArray(byteArray); // create URL request var request:URLRequest = new URLRequest(DOWNLOAD_URL); // send data via POST method request.method = URLRequestMethod.POST; // set data to send var variables:URLVariables = new URLVariables(); variables.image = byteArrayAsString; request.data = variables; var file:FileReference = new FileReference(); file.download(request, 'image.jpg'); } } }
And the PHP is only 1 line!
<?php echo base64_decode($_POST["image"]); ?>
Did I mention the final file size is less than 15KB? Oh, and if you really want a copy of the image on your server, just add some code to the PHP. I’ll be creating another blog post soon on round trip imaging that will include a number of operations together into one utility class.
Happy image creation!
Resources:
Saving Images From Flash
Saving Flash Graphics
hi!
i need to save on my server!
How can i do?
thanks a lot and really good tute!