How to Encode or Save BitmapData to PNG using Adobe AIR and Javascript

Jump to: navigation, search

If you are coding your Adobe AIR application in Javascript you can not access the ActionScript package directly. You will need to create an ActionScript file, compile it, and then import the resulting SWF into your application using a script tag. It is easy even if you are new to ActionScript. First create a file named with the following code. package { import flash.utils.ByteArray; import flash.display.BitmapData; import flash.display.Sprite; import; public class EncoderUtility extends Sprite { public static function encodePNG( bitmapData:BitmapData ):ByteArray { var encoder:PNGEncoder = new PNGEncoder(); var png:ByteArray = encoder.encode( bitmapData ); return png; } } } We next compile the above code using the amxmlc compiler. On a MAC it is found in the following directory: /Applications/Adobe Flash Builder 4/sdks/4.0.0/bin To run the compiler type the following on the command line: path_shown_above/amxmlc The compiler will produce an EncoderUtility.swf file. Now in your index.html add the following line <script type="application/x-shockwave-flash" src="lib/air/EncoderUtility.swf"></script> By adding the above line you can call the encoder in Javascript. Below is an example var data = new air.ByteArray; data = runtime.EncoderUtility.encodePNG(your_bmd); Finally if you want to save the byte array to a file use the following. var outFile = air.File.desktopDirectory; // dest folder is desktop outFile = outFile.resolvePath("bmd.png"); // name of file to write var outStream = new air.FileStream(); // open output file stream in WRITE mode, air.FileMode.WRITE); // write out the file outStream.writeBytes(data, 0, data.length); // close it outStream.close(); All of the above has been tested and works like a charm. This approach should also allow you to add other Flex packages such as a JPEG encoder.

See also

Use your Android as a Genie garage door opener remote

Personal tools