Search code examples
actionscript-3apache-flexmobilebitmapdata

Flex Mobile AS3, PersistenceManager storing/receiving BitmapData


I'm using the PersistenceManager to store data from my App. If I store BitmapData, it will stored correctly, but after a restart the BitmapData is now an Object. If I cast the Object to BitmapData it doesn't work.

pm.setProperty("sign", signArea.getBitmapData());

And this is the way I try to load it.

pm.getProperty("sign") as BitmapData;

If I doesn't stop the app, it would loaded correctly, but after a restart the "sign" is not BitmapData anymore. It's now an Object.


Solution

  • I don't think you can safely store an instance of BitmapData in a shared object (internally used in the PersistanceManager). It is not explicitly mentioned in the docs: http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/flash/net/SharedObject.html

    You can however save the data of the BitmapData as a ByteArray and convert is back when retrieving.

    // write
    var byteArray:ByteArray = bitmap.bitmapData.getPixels(bitmap.bitmapData.rect);
    so.data.byteArray = byteArray;
    so.data.width = bitmap.bitmapData.rect.width;
    so.data.height = bitmap.bitmapData.rect.height;
    so.flush();
    
    // read
    var byteArray:ByteArray = so.data.byteArray;
    var bitmapData:BitmapData = new BitmapData(so.data.width, so.data.height);
    bitmapData.setPixels(bitmapData.rect, byteArray);
    

    Notice that you'll also need to store the width and the height of the image. You could wrap this in an object so that you have 1 entry in the persistance manager instead of 3. This might be more convenient if you want to store multiple bitmaps.

    // write
    var bd:BitmapData = signArea.getBitmapData();
    var r:Rectangle = bd.rect;
    pm.setProperty("sign", {bytes:bd.getPixels(r), width:r.width, height:r.height});
    
    // read
    var signData:Object = pm.getProperty("sign");
    var bitmapData:BitmapData = new BitmapData(signData.width, signData.height);
    bitmapData.setPixels(bitmapData.rect, signData.bytes);