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.

astralmaster
  • 2,344
  • 11
  • 50
  • 84

2 Answers2

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);
Barış Uşaklı
  • 13,440
  • 7
  • 40
  • 66
  • hmm, interesting. Could you explain why it becomes synchronous? my guess is the draw() method waits for the loader to complete loading? – astralmaster Jul 18 '12 at 13:12
  • 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. – Barış Uşaklı Jul 18 '12 at 13:13
  • 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. – astralmaster Jul 18 '12 at 13:16
  • 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. – Barış Uşaklı Jul 18 '12 at 13:20
  • that's what I was thinking of as my last resort :) – astralmaster Jul 18 '12 at 13:23
  • It shouldn't be your last resort as it is not bad practice :) – Barış Uşaklı Jul 18 '12 at 13:24
  • Is there a reason you are using `Event.INIT` instead of `Event.COMPLETE` here? – IQAndreas Oct 07 '13 at 16:48
  • The documentation states you need to wait for the init event : http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/flash/display/Loader.html#loadBytes(). I am not sure if complete is fired before or after init. It is best to stick to what the documentation states. – Barış Uşaklı Oct 07 '13 at 20:16
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

brubs
  • 1,259
  • 8
  • 23
  • 2
    Loader would still be required for the image decoding, unless you write a custom decoder (which will decode slower than the native one) – SketchBookGames May 20 '13 at 15:39
  • This is a perfect solution if you are not using image encoders (ie: saving the byteArray "as is" to a file) – xleon Sep 18 '16 at 12:24