AS3 send BitmapData to backend efficiently

I was recently asked to send a medium/large file to a backend server running with php. At first I tried sending byteArray but that got messed up from JSON.strigify then I thought to convert the byteArray to base64 format. Although it worked an image of 500×700 occupied ~500kb on the database so it was unacceptable.
The solution was to compess the byteArray and send it, and then decompress it when I received it again. And here is how I did it:

public static function deconstructBitmap(bmp:BitmapData):Object
      // converting the bitmapdata into a byteArray
      var byteArray:ByteArray = bmp.getPixels(bmp.rect);
      // compressing using the default algorithm 'zlib'
      var enc:Base64Encoder = new Base64Encoder();  
      var b64;
      // joining all in one line
      b64 = enc.drain().split("\n").join("");
      // the rectangle is needed for re-contstruction
      return {'bmpData':b64,'rect':bmp.rect};

And now we have a compressed byteArray with our bitmapData the 500×700 bitmap data now occupies ~13kb on the database!

And here is the re-construction of the byteArray into bitmapData ready to be inserted to <s:Image/> or any other component.

public static function constructBitmap(obj:Object):BitmapData
      // to avoid errors
        var dec:Base64Decoder = new Base64Decoder();
        dec.decode(obj.bmpData); // decoding using the same algorithm
        var newByteArr:ByteArray=dec.toByteArray();
        // end of decoding //
        var bitmapData:BitmapData = new BitmapData(obj.rect.width, obj.rect.height);
        bitmapData.setPixels(bitmapData.rect, newByteArr);
        return bitmapData;
        return null;

And thats it, two simple functions to make you and your database happy!


Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *