Save Text as an Image in Flex

This could be a nice idea for saving a DisplayObject as an image file. Here i have done a sample workout which saves a DisplayObject (mx.controls.TextArea) as a PNG image file.  In the meantime, we can save all the DisplayObjects as an image file, but the DisplayObject should be implemented by IBitmapDrawable interface.

Since we don't have the feature like writing files into a physical path from Flash Player, we need  the help from a web server to write the ByteArrays into a file and to save  the file in the server path with respective extension. But if we worked out this sample in Adobe AIR, then we can save the image file  directly in the local path.

We can just follow the below steps to convert DisplayObject into image file.

  • Create a new BitmapData object with specified width and height and draw the DisplayObject into that.
  • Encode the BitmapData by using PNGEncoder class and it returns array of bytes.
  • Send the array of bytes to a web server by POST method.
  • Write the array of bytes into a file by the server scripts and save in a physical path.

MXML Code:

<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml"
				layout="vertical"
				backgroundColor="black">
<mx:Script>
<![CDATA[
import mx.graphics.codec.PNGEncoder;

private function saveAsImage():void
{
	var bitmapData:BitmapData = new BitmapData(txt.width, txt.height);
	bitmapData.draw(txt);
	var png:PNGEncoder = new PNGEncoder();
	var byteArray:ByteArray = png.encode(bitmapData);
	var urlRequest:URLRequest = new URLRequest();
	urlRequest.url = "http://yourdomain/byte-reciever.php";
	urlRequest.data = byteArray;
	urlRequest.method = URLRequestMethod.POST;
	urlRequest.contentType = 'image/png';
	var urlLoader:URLLoader = new URLLoader();
	urlLoader.load(urlRequest);
}
]]>
</mx:Script>
<mx:TextArea id="txt"
	 borderStyle="none"
	 text="We can save the TextArea control as PNG
 image from Flex application"
	 width="150"
	 height="150"
	 textAlign="center"/>
<mx:Button label="Save as image"
	   click="saveAsImage()"/>
</mx:Application>

PHP Server Code:

<?php
//Byte receiver 

$fp = fopen( 'Uploads/file.png', 'wb' );
fwrite( $fp, $GLOBALS['HTTP_RAW_POST_DATA' ] );
fclose( $fp );

?>

Please leave your comments if you need more on this. Thanks 🙂

Be Sociable, Share!

3 Responses to “Save Text as an Image in Flex”

  1. Kingz says:

    Really Good.

  2. Rohit Gupta says:

    Is there option to do it with Java instead of PHP?

    Regards,
    Rohit

  3. Ravi says:

    Hi,

    I need to store an image in database using flex. Please could you help me.

    Thanks,
    Ravi

Leave a Reply


Copyright © 2008-2010 K BalaSubramanian | Credits