Saving snapshots of HTML content in AIR
This can actually be done with any component that implements IBitMapDrawable, but I’m going to show you how it can be done with an HTML component specifically because, well, its cool. Feel free to use it to capture images of your web creations for portfolio purposes (in fact, I think I might just polish this up and make an real app to do just that).
To do this we just need an HTML component from which we can generate bitmap data using the BitmapData.draw() function. The bitmap data can then be encoded into a JPG ByteArray using the JPG encoder class available in AS3CoreLib. Once we’ve done that its just a matter of using a FStream to write those bytes to a File object with the appropriate extension (.jpg in this case). My example here writes the image to the desktop, but just a bit more code you could browse for a custom save location.
<?xml version="1.0" encoding="utf-8"?> <mx:WindowedApplication xmlns:mx="http://www.adobe.com/2006/mxml" layout="vertical" verticalScrollPolicy="off" horizontalScrollPolicy="off" width="1024" height="768" paddingLeft="0" paddingRight="0" paddingBottom="0" paddingTop="5" backgroundColor="#000000"> <mx:Script> <![CDATA[ import mx.managers.CursorManager; import mx.controls.Alert; import com.adobe.images.JPGEncoder; import flash.display.Bitmap; import flash.display.BitmapData; import flash.utils.ByteArray; import flash.filesystem.File; import flash.filesystem.FileMode; import flash.filesystem.FileStream; private function takeSnapShot() : void { var snapShot:File = File.desktopDirectory; snapShot = snapShot.resolvePath("AIRSnapshot.jpg"); var fStream:FileStream = new FileStream(); fStream.open(snapShot, FileMode.WRITE); var bitMapData:BitmapData = new BitmapData(htmlContent.width, htmlContent.height, false); var encoder:JPGEncoder = new JPGEncoder(80); var rawBytes:ByteArray = encoder.encode(bitMapData); fStream.writeBytes(rawBytes, 0, rawBytes.length); fStream.close(); Alert.show("Snapshot Saved to Desktop"); } ]]> </mx:Script> <mx:Button label="Take Snapshot" click="takeSnapShot()" color="#FFFFFF"/> <mx:HTML id="htmlContent" location="http://devote.your.life.auricom.com" width="100%" height="100%"/> </mx:WindowedApplication>
Hit this link link download the source and try it out.