Android how to save a bitmap – buggy code

Here is the code for a serialization with memory optimisation. Im using a static buffer that is growing to the biggest bitmap size and that I reuse each time.

public class Video implements Serializable{
public long videoId;
public String title;
public String publisher;
public String language;
public Date lastModified;
public Date published;
public String imageUrl;
public String url;
public Bitmap myVideoScreenshotBm;
public Date expireTime;
//public Drawable myVideoScreenshotDrawable;

private static ByteBuffer dst;
private static byte[] bytesar;

public Video (long newVideoId) {
    this.videoId=newVideoId;
}
private void writeObject(ObjectOutputStream out) throws IOException{

    out.writeLong(videoId);

    out.writeObject(title);
    out.writeObject(publisher);
    out.writeObject(language);
    out.writeObject(lastModified);
    out.writeObject(published);
    out.writeObject(expireTime);

    out.writeObject(imageUrl);
    out.writeObject(url);


    out.writeInt(myVideoScreenshotBm.getRowBytes());
    out.writeInt(myVideoScreenshotBm.getHeight());
    out.writeInt(myVideoScreenshotBm.getWidth());

    int bmSize = myVideoScreenshotBm.getRowBytes() * myVideoScreenshotBm.getHeight();
    if(dst==null || bmSize > dst.capacity())
        dst= ByteBuffer.allocate(bmSize);

    out.writeInt(dst.capacity());

    dst.position(0);

    myVideoScreenshotBm.copyPixelsToBuffer(dst);
    if(bytesar==null || bmSize > bytesar.length)
        bytesar=new byte[bmSize];

    dst.position(0);
    dst.get(bytesar);


    out.write(bytesar, 0, bytesar.length);

}

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

    videoId=in.readLong();

    title=(String) in.readObject();
    publisher=(String) in.readObject();
    language=(String) in.readObject();
    lastModified=(Date) in.readObject();
    published=(Date) in.readObject();
    expireTime=(Date) in.readObject();

    imageUrl = (String) in.readObject();
    url = (String) in.readObject();


    int nbRowBytes=in.readInt();
    int height=in.readInt();
    int width=in.readInt();

    int bmSize=in.readInt();



    if(bytesar==null || bmSize > bytesar.length)
        bytesar= new byte[bmSize];


    int offset=0;

    while(in.available()>0){
        offset=offset + in.read(bytesar, offset, in.available());
    }


    if(dst==null || bmSize > dst.capacity())
        dst= ByteBuffer.allocate(bmSize);
    dst.position(0);
    dst.put(bytesar);
    dst.position(0);
    myVideoScreenshotBm=Bitmap.createBitmap(width, height, Bitmap.Config.RGB_565);
    myVideoScreenshotBm.copyPixelsFromBuffer(dst);
    //in.close();
}

}

Leave a Comment