如何在Android中序列化位图



我试图保存对象列表的状态。对象类中的一个字段是位图。由于Bitmap是不可序列化的,我实现了我自己的Bitmap类,它实现了serializable。我已经看了其他问题来创建这门课,似乎它应该工作。但是当我运行应用程序时,它在执行serializableBitmap类中的writeObject方法后立即崩溃。但是当它崩溃的时候,它不会说它不幸停止工作了,它只是简单地回到主屏幕。它也不会在LogCat中输出任何错误消息。所以我不知道是什么导致了坠机。下面是我的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;
}
}

任何帮助都会非常感激。

哦,在包含位图的对象类中,我实现了Parcelable然后在writeToParcel方法中,我调用

dest.writeList(bitmaps);

位图是

private ArrayList<serializableBitmap> bitmaps; 

对于较大的位图,我也遇到了同样的问题。小一点的位图(大约500 x 300px)就可以了。

尽量避免序列化大的位图,而是在需要的地方加载它们。例如,您可以序列化它们的url并稍后加载它们或将它们写入本地存储。

最新更新