10 March 2008

User levelAdvanced
Required products
Adobe ColdFusion Enterprise Edition (2016 release) (Download trial)
Sample files

Additional Requirements

Flex 3 SDK (free with a trial of Flex Builder 3)
Flex Builder 3 (contains the free Flex 3 SDK)
The sample code files contain a complete test project to get you started with this technique.  It contains a sample Flex application and CFC that have all of the functions and capabilities in this article.  You can create the Flex project anywhere, however, the CFC and compiled Flex application should be deployed to the ColdFusion 8 server root directory. 
Have you ever wanted to take the visual output from a web-based Adobe Flex application, and save it as an image on your Adobe ColdFusion server?  Better yet, have you ever wanted to include that image in a PDF report?  Well, the combination of Flex 3 and ColdFusion 8 make this difficult-sounding task very easy for you.  With the following technique, you can export your Flex charts, still images from a webcam, or custom visualizations, and use them beyond the context of the browser.  In this article, you will learn how to code a real-world scenario of taking data from your Flex application, generating a chart, and exporting it to both JPG and PDF formats using ColdFusion 8.

Taking snapshots of Flex visual components

First, I'll explain the Flex side of things. All visual Flex components are rendered in memory as bitmap objects. Regardless of the type of visual object, you have access to that underlying bitmap data in ActionScript.  Flex 3 includes libraries for encoding both JPG and PNG images, and you can use these libraries to turn any rendered component into an image byte array.  The seemingly-difficult task of encoding an image, isn't really that complicated when you break it down.  You  can actually accomplish it with just one line of code.
The first thing to understand is how to get the JPG image from a Flex component.  The following function will allow you to pass in any visual Flex component (which descends from the DisplayObject class), and returns an encoded JPG image of that component, as follows.
private function grabScreen() : ByteArray { return ImageSnapshot.captureImage( chartsContainer, 0, new JPEGEncoder() ).data; }
This function takes advantage of the ImageSnapshot class, which copies the bitmap data from the target object and encodes it into a JPG using the ImageSnapshot class.  The ImageSnapshot class is new to Flex 3 and you can use it to extract images from any display object.   The first parameter is the target component that you are extracting graphics from. In this case it is a HLOC (high-low-open-close) Flex chart.  The second parameter is the DPI. In this case,  I'm using zero, which defaults the encoder to use the current screen resolution.  You can alter this value to change the resolution DPI (dots per inch) of the rendered image.  The third parameter is the encoder to use on the graphics object.  The default option is a PNG encoder.  In this case, we're using the Flex JPEGEncoder class.
Since this will work on any object that descends from the DisplayObject class, you can use it on any Flex component.   Some of the most popular cases for this are the Flex charting components.   This method allows you to use a Flex interface not only to filter and display the data, but also to preview and export a visualization of that data directly to the server.
Here is a simple Flex 3 HLOC chart example in MXML:
<mx:HLOCChart x="10" y="10" id="hlocchart1" dataProvider="{ data.item }" width="320" height="240"> <mx:series> <mx:HLOCSeries openField="open" closeField="close" highField="high" lowField="low"/> </mx:series> </mx:HLOCChart>
As you can see, there is nothing fancy about this chart.  It uses all the default settings of the HLOC chart, and has the dimensions 320 x 240 pixels.
One thing to keep in mind when you are encoding images in ActionScript is that the action of encoding an image is processor-intensive.   Your application may pause for a moment while the encoding operation takes place.  The larger the image, the longer it takes to encode.  In my experience, I have found that JPG encoding in ActionScript typically takes longer than PNG encoding.
Once you have the image data as a JPG encoded byte array, all that's left is persisting that image data to the server.  By far, the easiest way to do this is by using Flash Remoting to a ColdFusion component (CFC).   Flash Remoting uses the AMF (Active Message Format) protocol to serialize information in its native binary format.  This enables you to simply call a remote function from the Flex client and pass the image byte array directly to the server without the need to encode further.
In Flex, you will need to create an instance of the RemoteObject class.  You can see in the following example that the RemoteObject class instance is referencing the ScreenExports CFC on the ColdFusion server.  The endpoint, /flex2gateway/ refers to the mapping that is used by ColdFusion to handle AMF/RemoteObject requests. 
<mx:RemoteObject id="ro" endpoint="/flex2gateway/" destination="ColdFusion" source="ScreenExports" > <mx:method name="saveAsImage" result="onResult('Charts saved as JPG.')" fault="onFault(event)" /> <mx:method name="saveAsPDF" result="onResult('Charts saved as PDF.')" fault="onFault(event)" /> </mx:RemoteObject>
In this example, you can see that we have two methods for persisting data to the server.  Both correspond directly to functions within the ScreenExports CFC on the ColdFusion server.  When you want to persist data to the server, you must invoke one of these functions.  The following function takes the JPG encoded byte array from the grabScreen function, and passes it directly to the saveAsImage function defined in the RemoteObject instance.  
private function exportImageToJPG() : void { var data : ByteArray = grabScreen(); ro.saveAsImage( data ); }
That's all you need to do in Flex. 

Building the CFC component

Now, let's look at the CFC to see what happens on the server.  The ScreenExports CFC in this example contains two functions:  saveAsImage and saveAsPDF.  
The saveAsImage function takes one binary argument when it is invoked.  The method is scoped with a remote access attribute so that it is exposed publicly to the Flex client.  You can see that the logic of this function is actually quite simple.  It uses the CFFile tag to write the JPG-encoded binary data directly to the file system on the server as the file charts.jpg.  It also uses the CFImage tag to create a thumbnail of that JPG-encoded binary data. 
The CFImage tag is a great new feature of ColdFusion 8 that allows you to manipulate images within your ColdFusion applications.  You can find out more about the CFImage tag in the article, Image manipulation capabilities in ColdFusion 8.
<cffunction name="saveAsImage" access="remote" output="false" returntype="void"> <cfargument name="data" type="binary" required="true" /> <cffile action="write" file="c:\temp\charts.jpg" output="" /> <cfimage action="resize" height="40" width="100" source="" destination="c:\temp\thumbnail.jpg" overwrite="yes"> </cffunction>
Just for clarification, it is not necessary to write the image to the disk before creating a thumbnail of it.   If you did not want to keep the large version of the image, you could completely bypass the CFFile step and only use CFImage to generate a thumbnail.   The CFFile tag is not necessary to create the image thumbnail.  This example just shows you how to do both.
When exporting to a PDF, the Flex-side code is almost identical to the previous example.  The difference is that we are invoking the saveAsPDF remote method instead of the saveAsImage method.
private function exportImageToPDF() : void { var data : ByteArray = grabScreen(); ro.saveAsPDF( data ); }
The saveAsPDF CFC function takes one binary argument, the same as the saveAsImage function.  To export the image to PDF, you first need to write the image data to a JPG file on the local file system using the CFFile tag, and then export it to PDF using the CFDocument tag.  Unlike the previous example, the image file must be written to the file system.  When you write the temporary image to the file system, it needs to be in the web server's path so that it can be accessed by the CFDocument tag.  In this example, I am saving it to the web server root (C:\ColdFusion8\wwwroot\temp.jpg).   Notice that I am referencing it within the CFDocument tag as temp.jpg, which is the relative path to the web server root.  Once you have written the JPG file to disk, you can use the CFDocument tag to generate the PDF document.  This will also work with exporting to Flash Paper through the CFDocument tag . Use the localURL attribute if you are storing your temporary images on your server to improve performance when generating the PDF file.  Once your document has been created, you can clean up the temporary file.
<cffunction name="saveAsPDF" access="remote" output="false" returntype="void"> <cfargument name="data" type="binary" required="true" /> <cffile action="write" file="C:\ColdFusion8\wwwroot\temp.jpg" output="" /> <cfdocument format="PDF" filename="c:\temp\charts.pdf" overwrite="yes" localUrl="yes"> This is a generated PDF containing image data from Flex. <br><br> <img src="temp.jpg" > Enjoy! </cfdocument> <cffile action="delete" file="C:\ColdFusion8\wwwroot\temp.jpg" /> </cffunction>
It's that easy!  You can use this approach for a wide variety of applications: saving screen captures, saving webcam images, exporting charts, capturing user errors, and so forth.