Bitmap to ByteArray

Posted by Alexis on 23 April 2012 | 0 Comments

Tags:

I found this nifty method for saving out bitmap data from flash. It works a lot faster than using PNGEncoder and JPEGEncoder, this is obvious because no image encoding takes place, just the extraction of bytes. The down side is the filesize is a lot bigger being an uncompressed format uncompress. After testing it out I actually went back to PNGEncoder, becuase the application I'm building requires a lot of images. The disk space and load time trumps write speed.

However I did wrap the process into a handy little package bellow should anyone want to use it.

package au.com.dashdigital.utils
{
    import flash.display.Bitmap;
    import flash.display.BitmapData;
    import flash.utils.ByteArray;

    public class BitmapSerialize
    {
        public function BitmapSerialize()
        {
        }
        
        /**
         * Bitmap to ByteArray
         */
        public static function encode(bitmap:Bitmap):ByteArray {
            var bytes:ByteArray = new ByteArray();
            bytes.writeUnsignedInt(bitmap.bitmapData.width);
            bytes.writeBytes(bitmap.bitmapData.getPixels(bitmap.bitmapData.rect));
            bytes.compress();
            return bytes;
        }
        
        /**
         * ByteArray to Bitmap
         */
        public static function decode(bytes:ByteArray):Bitmap {
            var bitmap:Bitmap = null;
            try {
                bytes.uncompress();
                var width:int = bytes.readUnsignedInt();
                var height:int = ((bytes.length - 4) / 4) / width;
                var bmd:BitmapData = new BitmapData(width, height, true, 0);
                bmd.setPixels(bmd.rect, bytes);
                bitmap = new Bitmap(bmd);
            } catch (e:Error) {
                trace('BitmapSerialize error uncompressing bytes');                
            }
            return bitmap;
        }
    }
}

Post your comment

Comments

No one has commented on this page yet.

RSS feed for comments on this page | RSS feed for all comments