AS3: QuickHint: Convert BitmapData to ByteArray

While writing my next post, about Facebook and Flash development, I noticed that there is something in my post drafts that I haven’t published yet, so I changed it a bit and here you go.

On one of my last posts taking a screenshot with AS3 I’ve explained how to create a snapshot by using the Bitmap and the BitmapData classes.

Sometimes you need to convert the bitmaps to bytearrays to send them to a server-side script, save it directly to an AIR database or send it with AMF.

Something that is still a bit unclear, is how to convert the freshly created BitmapData to a ByteArray, there are no methods available in the default packages that come along with Flash Builder or Flash Professional, there are a few other ways, but they are in my opinion not really the best way on doing it. After all we all like to write short, smart clean code right?

Make sure you download the JPG/PNG Encoder classes from the AS3 corelib, without these you will not be able to create a proper bytearray of the snapshot,

To start off, let’s refresh our memory on how to create a bitmapdata.

_bitmapData					= new BitmapData( _sprite.width, _sprite.height );
_bitmap						= new Bitmap( _bitmapData );
_bitmapData.draw ( _sprite );
addChild( _bitmap );

Now that we remember how we create the bitmapdata object, let’s move on to the creation of a ByteArray, don’t be afraid it’s really easy, and it doesn’t cost you more then two lines of code.

var enc:JPGEncoder = new JPGEncoder( 80 );
var _snapshotBA = enc.encode( _bitmapData );

That was it, as you see, I kept my promise, only 2 lines of code to create a ByteArray.

Stay tuned for the next post.

Leave a comment

2 Comments.

  1. Thats a good way to get an encoded bytearray ready to send to some service or save on the local system(AIR).
    But if you just want the raw bytes from the BitmapData,
    you could just say:

    var ba:ByteArray = _bitmapData.getPixels();

    btw, for really fast jpeg encoding without alchemy I sugest you use thimbault´s class
    @bytearray.org
    or some alchemy magic

    Espero que ajude!

Leave a Reply

Your email address will not be published.


You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre lang="" line="" escaped="" highlight="">