Reputation: 4118
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);
}
}
}
Upvotes: 2
Views: 4371
Reputation: 37126
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
Upvotes: 1