How To: Parcel a bitmap in Android

FrinkTheBrave picture FrinkTheBrave · Sep 6, 2011 · Viewed 15.3k times · Source

I have a serialized class which I want to add a bitmap to, but Bitmap doesn't support serialize.

Instead I thought I'd use a parcel instead, but can't get it to work.

Here's some test code using local variables:

    Parcel parcel;
    Bitmap sourceBitmap;
    Bitmap destinationBitmap;
    parcel = Parcel.obtain();

    sourceBitmap = Bitmap.createBitmap(200, 400, Config.ARGB_8888);

    sourceBitmap.writeToParcel(parcel, 0);

    destinationBitmap = Bitmap.CREATOR.createFromParcel(parcel);

I get the following error on the last line above:

09-06 21:18:20.463: DEBUG/skia(17716): Bitmap_createFromParcel unknown config: 0
09-06 21:18:20.473: DEBUG/AndroidRuntime(17716): Shutting down VM
09-06 21:18:20.483: WARN/dalvikvm(17716): threadid=3: thread exiting with uncaught exception (group=0x4001b188)
09-06 21:18:20.493: ERROR/AndroidRuntime(17716): Uncaught handler: thread main exiting due to uncaught exception
09-06 21:18:20.513: ERROR/AndroidRuntime(17716): java.lang.RuntimeException: Failed to unparcel Bitmap
09-06 21:18:20.513: ERROR/AndroidRuntime(17716):     at android.graphics.Bitmap$1.createFromParcel(Bitmap.java:899)
09-06 21:18:20.513: ERROR/AndroidRuntime(17716):     at android.graphics.Bitmap$1.createFromParcel(Bitmap.java:903)

Answer

njzk2 picture njzk2 · Oct 11, 2011

you have to reset your parcel:

sourceBitmap.writeToParcel(parcel, 0);
parcel.setDataPosition(0);
destinationBitmap = Bitmap.CREATOR.createFromParcel(parcel);