2
我試圖在Android中保留圖像。我最終決定創建一個包裝對象來處理序列化。我預計它是次優的。在Android中序列化/反序列化圖像的最佳方式
我的問題:它怎麼能更好地完成(特別是關於性能,而不是遭受來自多個串行化的圖像退化)?
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);
}
}
}
在調用decodeByteArray(最後一行)之前沒有一行存在。您應該使用以下語句將輸入流讀入新創建的數組:in.readFully(imageByteArray)。在添加此行後,代碼很有用。 – Idan 2013-10-09 22:31:42