Best way to Serialize / Deserialize an image in Android

偶尔善良 提交于 2019-12-10 23:59:30

问题


I'm trying to persist images in Android. I eventually settled on the creating a wrapper object to handle serialization. I expect that it is sub-optimal.

My question: How could it be done better (especially with respect to performance and not suffering image degradation from multiple serializations)?

public class SerializableImage implements Serializable {

private static final long serialVersionUID = 1L;

private static final int NO_IMAGE = -1;

private Bitmap image;

public Bitmap getImage() {
    return image;
}

public void setImage(Bitmap image) {
    this.image = image;
}

private void writeObject(ObjectOutputStream out) throws IOException {
    if (image != null) {
        final ByteArrayOutputStream stream = new ByteArrayOutputStream();
        image.compress(Bitmap.CompressFormat.PNG, 100, stream);
        final byte[] imageByteArray = stream.toByteArray();
        out.writeInt(imageByteArray.length);
        out.write(imageByteArray);
    } else {
        out.writeInt(NO_IMAGE);
    }
}

private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException{

    final int length = in.readInt();

    if (length != NO_IMAGE) {
        final byte[] imageByteArray = new byte[length];
        in.readFully(imageByteArray);
        image = BitmapFactory.decodeByteArray(imageByteArray, 0, length);
    }
}
}

回答1:


Since PNG is lossless format you should have no degradation in quality. What you should watch for is not so much how you write/read image to/from file but how often you do it. I found that creating in-memory cache using weak references greatly reduces IO calls. Also be aware that even if you let system garbage collect the old images these are cached for longer times in the native code. The only call that helps you to deal with this is calling Bitmap.recycle



来源:https://stackoverflow.com/questions/9219023/best-way-to-serialize-deserialize-an-image-in-android

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!