Use Javascript to Take a Screenshot of a Flash Movie


By daniel - Posted on 06 March 2008

This is the first part of a tutorial for allowing a user to take a screenshot of a SWF and save it to their clipboard. In this section, we grab the image data in Flash, encode it as a PNG, and send it to Javascript.

I've been doing a lot of research lately on fetching an image of a SWF and embedding it in HTML, downloading it, and copying it to the clipboard. This page details how to take the screenshot and send the data to Javascript. It has been tested in Firefox and IE 6 & 7.

In the demo below, you can draw a masterpiece on the Flash canvas (left) and see it embedded in the webpage as an image (right).

Flash

Image

Take a picture with ActionScript 3.0

ActionScript 3.0 makes the initial task of acquiring the image quite simple. Assume the variable canvas_sp contains the Sprite that holds the user's artwork. All we have to do is create an instance of BitmapData and draw the sprite onto it.

var screenshotData:BitmapData = new BitmapData(450,300);
screenshotData.draw(canvas_sp);

At this point we have some raw bitmap data which we're going to encode as a PNG. Then, to ensure that it transmits safely as a string, we'll encode the PNG data in base64. You'll need the As3 Core Library for the PNG encoding and any one of a number of Base64 libraries. All free.

// first, convert the BitmapData into a PNG ByteArray
var pngBytes:ByteArray = PNGEncoder.encode(screenshotData);
 
// and then convert that into base64
var screenshotBase64:String = Base64.encodeByteArray(pngBytes);

Now we need to build the external interface so Javascript can get a hold of the image data.

Getting the bitmap data to Javascript

// setup the interface method in your initialization function
private function init():void
{
	ExternalInterface.addCallback('getScreenshot',
		interfaceIn_getScreenshot);
}
 
// this is the function that gets called by Javascript.  it
// returns the screenshot data as a base64-encoded string
private function interfaceIn_getScreenshot():String
{
	var w:Number = 50;
	var h:Number = 50;
 
	var screenshotData:BitmapData = new BitmapData(w, h);
	screenshotData.draw(this);
 
	return Base64.encodeByteArray(
          PNGEncoder.encode(screenshotData));
}

Note that the code from the section above has been compressed into a single line at the end, there. And that's it for the Flash side of things! Now, in the Javascript of the embedding page, you make a call to getScreenshot and you'll have string representing the screenshot taken in Flash.

// flashElem is the Player's <embed> or <object> tag
var screenshotBase64 = flashElem.getScreenshot();

That's it for this little guide. In the next part I'll go into embedding the base64 image into the web page.