Copyright © 2010 K Balasubramanian. Snowblind theme by c.bavota & Juan Gordillo. Powered by WordPress.
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
The Save Text as an Image in Flex by K Balasubramanian, unless otherwise expressly stated, is licensed under a Creative Commons Attribution-Noncommercial 2.5 India License.


November 14, 2009 at 4:11 pm
Really Good.
December 4, 2009 at 1:42 am
Is there option to do it with Java instead of PHP?
Regards,
Rohit