2012/08/02

To Export Images in Flex

There are several procedures to realize image exporting in Flex.
1.Make a UI component and draw the content to be exported on it.
2.Making a BitmapData object and draw the UI component into it.
3.Convert the contents of BitmapData into binary data of ByteArray through PNGEncoder or JPEGEncoder.

You must have the image data in RAM after the above procedures. You are quite lucky if you have TWaver’s Network component, for by the means of the function exportAsBitmapData(logicalRect:Rectangle = null, zoom:Number = 1):BitmapData of network you are able to convert any area of a image of any percentage into a BitmapData object.

But here it is the Last Mile that really matters. The image information in the RAM is invisible and untouchable, so generally we need to export it to local files. The traditional method we took before is to transmit the binary data of ByteArray to the background by means of HTTP, and then redirected it as an issued file to be saved by users. Undoubtedly, this method was of much demerits: data at the client side had to take the trouble to transmit to the server-side and then returned to the same side. In an age of green and conservation, this method seems like “crime.” Fortunately, Adobe succeeded in adding a green and conservative function FileReference.save(), thus enabling us to save the data of the RAM of the client-side in the local hard disk.

You may have found that only Flex4 has the function FileReference.save() . In fact, there are many projects which are developed on the basis of SDK of Flex3 now, including TWaver Flex Demo. How can we use this function in products based on Flex3? You could find the answer in TWaver Flex Demo. Just two steps:

Step 1: Introducing in the FileReference object which is of the class Object in the code. By using Object of dynamic, you could call a function or compile the passing conditions. But you need to write the function hasOwnProperty to judge whether direct image-saving can be realized.
public static function addExportButton(toolbar:Box, network:Network):Button{
    return addButton(toolbar, "Export Image", DemoImages.export, function():void{
              var fr:Object = new FileReference();
              if(fr.hasOwnProperty("save")){
                  var bitmapData:BitmapData = network.exportAsBitmapData();
                  var encoder:PNGEncoder = new PNGEncoder();
                  var data:ByteArray = encoder.encode(bitmapData);
                  fr.save(data, 'network.png');
              }else{
                  Alert.show("install Flash Player 10 to run this feature", "Not Supported");
              }
    });
}

1 comment:

  1. A lot of great info, thanks so much! My friend has recently been interested in image-flex and got me fairly interested too. We've been searching out any info we can find. Do you have any other advice for those just starting out? Any feedback you have would be appreciated, thanks!

    ReplyDelete