Save Chart as Image

This tutorial shows you how to save the chart as an Image

ImageSnapshot
Using ImageSnapshot’s captureImage method we can capture any IBitmapDrawable object and it return ImageSnapshot through it we use it’s data property as byte array so we can make duplicate image object of any IBitmapDrawable object.

var image:ImageSnapshot = ImageSnapshot.captureImage(Overall, 0, new JPEGEncoder() );  //Where overall is the ID for UIComponent
private var file:FileReference = new FileReference();
file.save(image.data, “chart.jpg”);

ChartData.xml

<xml>
<data>
<row Title=’Nov’ Y10=’326526′ Y09=’273832′ Y08=’313892′ />
<row Title=’Dec’ Y10=’302275′ Y09=’300582′ Y08=’281679′ />
<row Title=’Jan’ Y10=’332562′ Y09=’340447′ Y08=’275207′ />
<row Title=’Feb’ Y09=’280497′ Y08=’247873′ />
<row Title=’Mar’ Y09=’328304′ Y08=’303520′ />
<row Title=’Apr’ Y09=’366068′ Y08=’314591′ />
<row Title=’May’ Y09=’286720′ Y08=’363357′ />
</data>
</xml>

ChartToImage.mxml

<?xml version=”1.0″ encoding=”utf-8″?>
<mx:Application xmlns:mx=”http://www.adobe.com/2006/mxml” layout=”absolute” initialize=”initializeHandler();” height=”100%” >
<mx:Script>
<![CDATA[
import mx.graphics.codec.JPEGEncoder;
import mx.graphics.ImageSnapshot;
private var file:FileReference = new FileReference();
private function initializeHandler():void
{
var XMLLoader2:URLLoader=new URLLoader(new URLRequest(“ChartData.xml”))
XMLLoader2.addEventListener(Event.COMPLETE,xmlLoaded2)
function xmlLoaded2(event:Event):void
{
var myXML:XML = XML(event.target.data);
var FinalXML:XMLList=new XMLList(XML.data.row)
BarChart.dataProvider=FinalXML;
}
}
private function SaveImage(e:Event):void
{
var image:ImageSnapshot = ImageSnapshot.captureImage(Overall, 0, new JPEGEncoder() );  //It captures the panel data [Overall] which has the ColumnChart in it.
file.save(image.data, “chart.jpg”); //Image is the ImageSnapshot. Image.data has the jpeg data
}
]]>
</mx:Script>
<mx:Panel id=”Overall” title=”Over All Traffic” x=”10″ y=”10″ width=”500″ height=”400″>
<mx:ColumnChart x=”10″ y=”10″ showDataTips=”true” id=”BarChart” width=”100%” height=”308″>
<mx:horizontalAxis>
<mx:CategoryAxis categoryField=”@Title” />
</mx:horizontalAxis>
<mx:series>
<mx:ColumnSeries displayName=”FY10″ yField=”@Y10″ showDataEffect=”seriesInterpolate”/>
<mx:ColumnSeries displayName=”FY09″ yField=”@Y09″ showDataEffect=”seriesInterpolate”/>
<mx:ColumnSeries displayName=”FY08″ yField=”@Y08″ showDataEffect=”seriesInterpolate”/>
</mx:series>
</mx:ColumnChart>
<mx:Legend dataProvider=”{BarChart}” direction=”horizontal” />
</mx:Panel>
<mx:Button x=”518″ y=”19″ label=”Save Chart” click=”SaveImage(event)” /></mx:Application>