user3753848
user3753848

Reputation: 41

How to Serialize a Bitmap in Android

I am trying to save the state of a list of objects. And one of the fields in the object class is a bitmap. And since Bitmap is not serializable I have implemented my own bitmap class that implements Serializable. I have looked at other questions to create this class and it seems that it should work. But when I run the application it crashes right after it executes the writeObject method in my serializableBitmap class. But when it crashes it doesn't say that it unfortunately stopped working but it just simply goes back to the home screen. It also does not output any error messages in the LogCat. So I have no idea what is causing the crash. Here is my serializableBitmap class:

public class serializableBitmap implements Serializable {


private static final long serialVersionUID = -5228835919664263905L;
private Bitmap bitmap; 

public serializableBitmap(Bitmap b) {
    bitmap = b; 
}

// Converts the Bitmap into a byte array for serialization
private void writeObject(ObjectOutputStream out) throws IOException {
    ByteArrayOutputStream byteStream = new ByteArrayOutputStream();
    boolean success = bitmap.compress(Bitmap.CompressFormat.PNG, 0, byteStream);
    byte bitmapBytes[] = byteStream.toByteArray();
    if (success)
    out.write(bitmapBytes, 0, bitmapBytes.length);
}

// Deserializes a byte array representing the Bitmap and decodes it
private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException {
    ByteArrayOutputStream byteStream = new ByteArrayOutputStream();
    int b;
    while((b = in.read()) != -1)
        byteStream.write(b);
    byte bitmapBytes[] = byteStream.toByteArray();
    bitmap = BitmapFactory.decodeByteArray(bitmapBytes, 0, bitmapBytes.length);
}

public Bitmap getBitmap() {
    return this.bitmap;
}

}

Any help would be so much appreciated.

Oh and in my object class that contains the bitmap i implement Parcelable and then in the writeToParcel method I call

dest.writeList(bitmaps);

And bitmaps is

private ArrayList<serializableBitmap> bitmaps; 

Upvotes: 3

Views: 5349

Answers (1)

miracula
miracula

Reputation: 527

I had the same problem for larger Bitmaps. Smaller Bitmaps (ca. 500 x 300px) worked just fine.

Try to avoid serializing large Bitmaps and load them where they are needed instead. You could for example serialize their URLs and load them later or write them to local storage.

Upvotes: 1

Related Questions