ByteArray to BitmapData AS3
Asked Answered
P

2

6

I'm using com.adobe.images.PNGEncoder to encode bitmapData to a byteArray. Is there a way to convert the byteArray back to bitmapData NOT using a Loader? thanks.

EDIT: the reason i don't want to use a Loader is it being Asynchronous, and I don't want to implement eventlisteners.

Piemonte answered 18/7, 2012 at 12:46 Comment(0)
V
10

The following is using the loader class but is synchronous.

var loader:Loader = new Loader();
loader.loadBytes(byteArray);
bmpData.draw(loader);

Edit: Nevermind the loadBytes is asynchronous too, the documentation says you need to wait for the init event. What is the reason for not wanting event listeners? They are a pretty common practice in AS3.

So you need something like this :

var loader:Loader = new Loader();
loader.contentLoaderInfo.addEventListener(Event.INIT, function(e:Event):void {
   bmpData.draw(loader);    
});
loader.loadBytes(byteArray);
Villar answered 18/7, 2012 at 13:8 Comment(8)
hmm, interesting. Could you explain why it becomes synchronous? my guess is the draw() method waits for the loader to complete loading?Piemonte
See my edit it turns out it is not synchronous so you will have to still use the init event handler I will edit the answer.Secretary
oh. You see I have a loop which should contain the .loadBytes() method and it's going to iterate 10 or maybe more times. and the resulting bitmapData is also needed inside the loop. that makes me wonder how would I do it using the event listeners.Piemonte
In that case you will wrap the code inside the loop in a function. That will ensure the bmpdata used in the event listener is the correct one.Secretary
that's what I was thinking of as my last resort :)Piemonte
It shouldn't be your last resort as it is not bad practice :)Secretary
Is there a reason you are using Event.INIT instead of Event.COMPLETE here?Falcate
The documentation states you need to wait for the init event : help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/…. I am not sure if complete is fired before or after init. It is best to stick to what the documentation states.Secretary
Q
2

Take a look on the setpixels() method of bitmapdata. It requires a rectangle to define the size and a bytearray as content. This method synchronous

Queensland answered 18/7, 2012 at 14:52 Comment(2)
Loader would still be required for the image decoding, unless you write a custom decoder (which will decode slower than the native one)Sueannsuede
This is a perfect solution if you are not using image encoders (ie: saving the byteArray "as is" to a file)Boresome

© 2022 - 2024 — McMap. All rights reserved.