简体   繁体   English

如何在Android中序列化位图

[英]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. 由于Bitmap不可序列化,因此我实现了自己的实现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. 但是当我运行应用程序时,它在我的serializableBitmap类中执行writeObject方法后立即崩溃。 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. 它也不会在LogCat中输出任何错误消息。 So I have no idea what is causing the crash. 所以我不知道导致崩溃的原因。 Here is my serializableBitmap class: 这是我的serializableBitmap类:

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 哦,在我的对象类中包含我实现Parcelable的位图,然后在我调用的writeToParcel方法中

dest.writeList(bitmaps);

And bitmaps is 位图是

private ArrayList<serializableBitmap> bitmaps; 

I had the same problem for larger Bitmaps. 我对更大的位图有同样的问题。 Smaller Bitmaps (ca. 500 x 300px) worked just fine. 较小的位图(约500 x 300px)工作正常。

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. 例如,您可以序列化其URL并在以后加载它们或将它们写入本地存储。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM