Search Flex Samples

Taking a snapshot of Flex app, from Flex!

On a recent Flex project, we needed to take a snapshot of what's shown on the screen and save it as an image. I had seen somewhere that this was possible, but couldn't locate how exactly it was to be done. Turns out it's very easy to do such a screen capture / screen grab using Flex.
The essential steps are:
Create a new BitmapData object.
Copy the target component's pixel data into BitmapData object.
Convert the BitmapData object to a PNG encoded ByteArray (using the PNGEnc library)
Convert the ByteArray to a Base64Encoded string so that we can send the data safely to the backend.
On the backend (PHP via WebORB in our case), decode the data and write it to a file.
Most of the piece come from two places. James Ward has described this technique in his Flex Paint sample. And Tinic Uro has written the PNG Encoder library. Let's see the code now.
Here's the Flex Code:
PLAIN TEXT
XML:



import mx.utils.Base64Encoder;
import mx.rpc.events.ResultEvent;
import mx.utils.ObjectUtil;
import mx.controls.Alert;
import mx.rpc.events.FaultEvent;
import mx.core.UIComponent;

public function onResult(event:ResultEvent) :void
{
Alert.show(ObjectUtil.toString(event.result));
}

public function onFault(event:FaultEvent) :void
{
Alert.show("Got error: "+event.message);
}

public function takeSnapshot(target:UIComponent) :void
{
var bd:BitmapData = new BitmapData(target.width,target.height);
bd.draw(target);
var ba:ByteArray = PNGEnc.encode(bd);
var be:Base64Encoder = new Base64Encoder();
be.encodeBytes(ba);
var encodedData:String = be.flush();
ro.saveImage(encodedData);
}
]]>












We use WebORB for backend connectivity. Assuming you have the connection in place, we can simply call a method passing the base 64 encoded string and save it on the server. If you don't have RemoteObject / Web Service, you can also use an HTTP POST. The reason to use Base 64 encoding is to get a string we can safely pass around, instead of a byte array.
Here's the PHP side of the code:
PLAIN TEXT
PHP:
public function saveImage($encodedPNGData)
{
if ($encodedPNGData != "")
{
$binaryData = base64_decode($encodedPNGData);
$file = "assets/images/something.png";
file_put_contents($file, $binaryData);
return $file;
}
return null;
}
I could resize and do anything else with the image on the PHP side now.

0 comments:

Related Flex Samples

Learn Flex: Flex Samples | Flex Video Tutorials Flex Examples