*** UPDATE ***
In my post below; I am mentioning 1 out of 2 possible ways of embedding image (or any other format for that matter) into an AS3 project but here is link to a detailed post by Renaun Erickson mentioning both the techniques.
I have been developing an Adobe AIR application for the last 2-3 weeks and so far, it has only been a simple yet big (in terms of content) interactive presentation running on the desktop. Just recently, I was asked to see if there is any way some images could be copied to user’s desktop when the application is being installed or is being run so that the user can select those images to set as wallpaper.
As always, I started my journey with googling but soon realized that there is no direct way of copying images from development environment to a user’s desktop via AIR application. The solution I figured out was as follows and please, if someone knows a better way around this; let me know.
As a note; my main development IDE was Flash CS4 Professional and I used FlashDevelop as code-editor.
I first embedded the images I wanted to carry with my application using the [Embed] metadata tag; which is a part of Flex SDK. Attached a Class to it obviously and then instantiated in code.
private var Wallpaper :Class;
private var wallpaper :Bitmap = new Wallpaper ();
Then it was about creating a folder on user’s desktop. It uses File class of AIR API.
var directory :File = File.desktopDirectory.resolvePath ( 'Wallpapers' );
Then it was about writing a JPG file.
this.file = File.desktopDirectory.resolvePath ( 'Wallpapers/Wallpaper.jpg' );
The above code doesn’t write the file instantly as you can see we haven’t yet connected our embedded image to this file in anyway but instead it creates a placeholder, a blank image file which has nothing but 0 bytes yet.
The FileStream class of AIR API is the one providing the necessary methods of opening/reading/writing bytes on a file but since it only allows ByteArray to be written on to a File instance, I had to first convert my embedded image data into ByteArray data. as3corelib comes in handy again. JPGEncoder class of this package provides us with encode method which converts BitmapData to ByteArray.
var imageByteArray:ByteArray = this.jpgEncoder.encode ( this.wallpaper.bitmapData );
And finally, it was about opening the File instance and feeding this imageByteArray data to it using our FileStream instance.
this.outputProgressed.addOnce ( this.onProgress_CopyFiles );
this.fileStream.openAsync ( this.file, FileMode.WRITE );
this.fileStream.writeBytes ( imageByteArray );
I used openAsync instead of open because I wanted the other code to run at the same time while the images were being copied in the background. Plus, since I used Robert Penner’s AS3Signals as my main event mechanism throughout this application, I used the lovely addOnce method to make sure the listener object gets removed once the event is fired.