Capturing UIComponents as Bitmap or encoded ByteArray

Published 2009-04-25 By SDS

"Screenshot" of a flex component

We found useful to have a simple static class helping us to quick capture parts of the flex application(or specific components) as Bitmap or encoded ByteArray, ready to be sent server-side to be saved as image (or simply saved from AIR app).  Here is the class, maybe you can find it usefull for your projects:

package
{
	import flash.display.Bitmap;
	import flash.display.BitmapData;
	import flash.geom.Matrix;
	import flash.geom.Rectangle;
	import flash.utils.ByteArray;
 
	import mx.core.IUIComponent;
	import mx.graphics.codec.JPEGEncoder;
	import mx.graphics.codec.PNGEncoder;
 
	public class ScreenCapture
	{
 
		static private var bitmap:Bitmap;
		static private var bitmapData:BitmapData;
 
		static public const JPEG:String	= "jpeg";
		static public const PNG:String	= "png";
 
		/**
		 * Return a bitmap instance based on params
		 */
		static public function getBitmap(area:Rectangle, fromTarget:IUIComponent):Bitmap
		{
			bitmapData	= new BitmapData(area.width,area.height);
			bitmap		= new Bitmap(bitmapData);
 
			var matrix:Matrix	= new Matrix();
			matrix.tx	= area.x;
			matrix.ty	= area.y;
 
			bitmapData.draw(fromTarget,matrix);
			return bitmap;
		}
 
		/**
		 * returns a byte array encoded as specified in imageFormat argument
		 * Values are JPEG and PNG.
		 */
		static public function getImage(area:Rectangle, fromTarget:IUIComponent,imageFormat:String="jpeg",quality:Number=80):ByteArray
		{
			getBitmap(area, fromTarget);
 
			if ( imageFormat	== PNG)
			{
				return encodePNG();
			}
			return encodeJPEG(quality);
		}
 
		/**
		 * Encodes as jpeg with specified quality
		 */
		static private function encodeJPEG(quality:Number):ByteArray
		{
			return (new JPEGEncoder(quality)).encode(bitmapData);
		}
 
		/**
		 * Encodes as png
		 */
		static private function encodePNG():ByteArray
		{
			return (new PNGEncoder()).encode(bitmapData);
		}
 
	}
}

and here is an example of use.
Enjoy it!

		/**
		 * Example function to get Bitmap object
		 */
		public function getCapture():void
		{
			var bitmap:Bitmap	= ScreenCapture.getBitmap(new Rectangle(0,0,cmp.width,cmp.height),cmp);
			rawChildren.addChild(bitmap);
		}
 
		/**
		 * Example function to get enoded ByteArray as jpg or png
		 */
		public function getImageEncoded(imageType:String):void
		{
			var bytearray:ByteArray	= ScreenCapture.getImage(new Rectangle(0,0,cmp.width,cmp.height),cmp,ScreenCapture.JPEG,85);
			//	var bytearray:ByteArray	= ScreenCapture.getImage(new Rectangle(0,0,cmp.width,cmp.height),cmp,ScreenCapture.PNG);
			//	.... rest of code to handle bytearray to be saved ...(server side or using AIR...)
		}

Comments

No comments

Comments are closed for this article.