Downloading and Saving Images to the desktop with AIR

In this example i want to show you how to download remote image(jpg or png) and save it to the desktop.
Load remote file. We use Loader Class and listen for complete event. We call load method and pass URLRequest parameter.
private function loadRemoteImage(url:String):void { var loader:Loader = new Loader(); loader.contentLoaderInfo.addEventListener(Event.COMPLETE, completeHandler); loader.load(new URLRequest(url)); }
Create a BitmapData object. We can access BitmapData object through Bitmap object. In our example Bitmap object is the same as loaderInfo.content.
FOR DEMO PURPOSES ONLY: Image (<mx:Image id=”img”/>) component shows downloaded image.
private function completeHandler(event:Event):void { var loaderInfo:LoaderInfo = event.target as LoaderInfo; img.source = loaderInfo.content; var bitmap:Bitmap = loaderInfo.content as Bitmap; _bitmapData = bitmap.bitmapData; }
Encode image to JPEG or PNG. Before saving image, we have to take the current BitmapData object and encode to the ByteArray object. This ByteArray object needs to be encoded in the proper format and for this we can use the JPEGEncoder and PNGEncoder.
private function saveImage():void { var imgByteArray:ByteArray; var extension:String; if(textInput.text.toLowerCase().indexOf('.jpg') != -1) { // encode to JPEG var jpegEncoder:JPEGEncoder = new JPEGEncoder(80); imgByteArray = jpegEncoder.encode(_bitmapData); extension = '.jpg'; } else if(textInput.text.toLowerCase().indexOf('.png') != -1) { // encode to PNG var pngEncoder:PNGEncoder = new PNGEncoder(); imgByteArray = pngEncoder.encode(_bitmapData); extension = '.png'; } else return; ...
Save file to the desktop. Now that we already have the encoded ByteArray, we just need to save it to a local file. We do this using the File and FileStream classes.
... var file:File = File.desktopDirectory.resolvePath('test'+extension); var fileStream:FileStream = new FileStream(); fileStream.open(file, FileMode.WRITE); fileStream.writeBytes(imgByteArray); fileStream.close(); }


Sharad
April 21, 2009 at 6:34 pm
Thanks for this post. This was a lifesaver, really
I spent two days figuring out this and then came across your post.
It is actually weird that we need to reencode the downloaded bytes. loaderInfo.content should already have the data, but it appears that flash adds some extra headers in front of the received data. This data, when saved as is, can not be opened by any app other than flash. Nuts!
Rui
June 26, 2009 at 5:37 pm
Brilliant tutorial, saved my life
thank you!!