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.