This is a question I see asked fairly regularly, yet it seems to be a hard one to google for and get an easy answer.
In my current main project I have a need to pre load a large amount of images as quickly as possible, and yet kill any existing preloads immediately should circumstances change. Some casting around lead me to the StreamLoader class which offers all I needed, with the proviso that the result is a raw ByteArray.
So, I needed a means to convert that ByteArray to a bitmap or BitmapData.
Some digging around lead me to the fact that the Loader class will do that for a ByteArray that is read from a jpeg or png file.
The code looked something like this for an existing ByteArray in a variable named “bytes” :
var loader:Loader = new Loader();
loader.loadBytes(bytes);
Now, the bitmap *will* be available in the loaders “content” property, but do not assume that just because you gave it a preloaded bytearray that it will be *immediately* available. Or you will be sad and confused, as was I
No, the bitmap will only be available once the loader.contentLoaderInfo complete event fires.
So, add an event listener for the complete event :
loader.contentLoaderInfo.
Then get the bitmap from the loader at that point in time :
private function loaderCompleteHandler(event:
{
var loader:Loader = event.target as Loader;
var bmp:Bitmap = Bitmap(loader.content);
}
Note that I’ve omitted all the usual removing of event listeners, unloading loaders etc for the sake of brevity.
So there you go, that’s how it’s done. Now I know the answer it makes perfect sense, but initially it did seem to work not quite as I expected it to.
Since then I’ve had occasion to use this a couple more times, such as getting a server side processed image from .NET via fluorine remoting services, and in AIR (grabbing images stored as ByteArray blobs in a sqlite database).
Reference:http://ifeedme.com/
No comments:
Post a Comment