Thursday, October 27, 2011

Loading images from applicationStorageDirectory in Flex Mobile

I have to say, without a doubt, this was one of the most confounding things I've worked on in a long, long, long time. In a project for my client, I have to be able to store zip files filled w/ media assets, then be able to load audio or pictures at runtime.

 Sounds easy, right? Wrong :(

 Loading a picture has never been this painful in my life. It turns out, I can add the image to the stage (which for some reason is not respecting my skin, contentgroup, or vertical layout settings). Regardless, I can finally load any stored image via this "not-so" simple routine.  One caveat I have is, I am downloading images in zip format, and using a utility to unpackage them into the storage directory in folders.  originally I though that would be a problem, but it turns out, because I can update the file.nativePath with the new folder, this works just fine.

var fl:File = File.applicationStorageDirectory;
fl.nativePath = fl.nativePath + _image;
var bytes:ByteArray = new ByteArray();
var filestream:FileStream = new FileStream();
try{, FileMode.READ);
filestream.readBytes(bytes, 0, filestream.bytesAvailable);
loader = new Loader();
loader.contentLoaderInfo.addEventListener(Event.COMPLETE, showPic);
loader.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR, onError);
}catch (e){
trace("xml badly formed");

and in my showPic method:

loader.contentLoaderInfo.removeEventListener(Event.COMPLETE, showPic);
var bitmapData:BitmapData = new BitmapData(loader.content.width,loader.content.height, true, 0x000000);
bitmapData.draw(loader.content, new Matrix(),null,null,null,true);
img.source = new Bitmap(bitmapData);

Honestly, painful, but it gets the job done.  Now to load audio dynamically from saved files is another story for another post:)


  1. thanks for this code man, i was about to smash the place up

  2. Was this iOX or Android? It's working fine on Android but giving a "File Downloads Not Supported" error on iPhone/iPad.

    1. @Velocedge - this was iOS 4.x. What iOS are you running against?

  3. oh God, if you make this work I promise I'll believe in you again! ... ok, that was a total lie.
    Thanks for publishing this, I've been messing with this nonsense since this morning. I'm crossing my fingers man!

  4. hi freid I talk from Brazil, You can code complete ??

  5. ooooohhh... finally worked...
    THANK YOU :)