This was a non trivial issue prior to Flex 3 - most people had approached this using a mix of client and server side technologies, even using javascript as well. But most of the solutions were not simple or elegant, this is where Flex3 came to the rescue with the
ImageSnapshot class.
Doug McCune created an interesting approach using javascript and serializing image bytes to the browser address bar, although not simple, it is creative and that dynamic chart is great.
Today it is a very simple thing to do. It is a two fold problem with a very easy implementation thanks to the awesome flex framework.
Graham Odds wrote a great article on how to do this and I'm elaborating on his article.
- Save the UIComponent as an image (you can specify the image format) using the ImageSnapshot class
- Send the image to be saved to the user's computer (using the FileReference class from Flash 10)
All
UIComponents in flex extend
DisplayObject which can be exported to an image, e.g. png,, jpg, etc using the
ImageSnapshot class. Currently there are two classes that can take BitMapData or ByteArray and convert them to an image format, class that implement interface
IImageEncoder allow this. The image encoders are:
JPEGEncoder and
PNGEncoder. Once it is exported to an image, the byte data can now be transferred to the user's computer and saved as a file.This is done using the
FileReference class introduced in Flash 10.
Below is the code snippet to do this (
source) :
/**
* Attempts to save the chart to the user's file-system.
*/
private function saveChart():void
{
var image:ImageSnapshot = ImageSnapshot.captureImage(myChart, 300, new PNGEncoder());
var file:FileReference = new FileReference();
file.save(image.data, "chart.png");
}