Saving remote images locally in an AIR app

Very briefly the approach you need to follow is to use the URLLoader class to download the image(s) in question and make sure you set the _urlLoader.dataFormat = URLLoaderDataFormat.BINARY.

In the Event.COMPLETE event handler you will be able to access the ByteArray data via urlLoader.data. All you need to do is write that to a file: fileStream.writeBytes( loader.data, 0, loader.data.length );

I would go into the details of this but Brian Rinaldi and Mihai Corlan have both written excellent and concise posts about it.

I’m only blogging about this because I spent days doing this the wrong way until finally realizing, “wait a second, this can’t be right.” You see I was using the Loader class to download the images. That works of course. But you end up with a Bitmap in the event.target.content and don’t have access to the actual ByteArray of the image that you downloaded.

That approach is just fine if all you want to do is display an image. But if you want to save it to disk then you have to go through the intermediary step of pulling the ByteArray out of the Bitmap using the JPEGEncoder or PNGEncoder. That is a wasteful step when you can just get the ByteArray data directly using the URLLoader. Plus it can be quite time consuming for large images which will halt your app while it chews on the data.

So thank you Brian and Mihai for showing me the light. :-)

Tags: ,