Tuesday, September 15, 2015

Android: Saving Bitmap as Serializable Object

The Problem

In Android you cannot save the any bitmap Object as serilizable objects and you cannot add implement Serializable Interface as it is a final class.
so In general the problem is "Saving bitmap Images as Serializable Object"


The Solution

Luckily there is a very simple way to do this
Those who are experts of you will find the next two lines sufficient

bitmapObject.getPixels(pixels,0,width,0,0,width,height);
 &
Bitmap.createBitmap(pixels, width, height, Bitmap.Config.ARGB_8888);

Still not getting it

Well here it is how,

  • First we create a simple class, we will call it ProxyBitmap, why use the word "proxy" ?
    public class ProxyBitmap
  • Make the class serializable
    public class ProxyBitmap implements Serializable {}
  • Add the following attributes
    private final int [] pixels;
     // this array will hold the pixels of the bitmap Image
    
    private final int width , height;
    // those will hold both the width and height attributes
  • Now adding the constructor, we take bitmap as input in the constructor to get its pixel data.
    public ProxyBitmap(Bitmap bitmap){
       width = bitmap.getWidth();
       height = bitmap.getHeight();
       pixels = new int [width*height];
       bitmap.getPixels(pixels,0,width,0,0,width,height);
    }
  • Now to create a method that will return the bitmap object
    
    public Bitmap getBitmap(){
        return Bitmap.createBitmap(pixels, width, height, Bitmap.Config.ARGB_8888);
    }
  • The whole class will look something like this according to your preference 
    
    import android.graphics.Bitmap;
    import java.io.Serializable;
    /** * Created by John on 07-Sep-15. */
    public class ProxyBitmap implements Serializable{
        private final int [] pixels;
        private final int width , height;
    
        public ProxyBitmap(Bitmap bitmap){
            width = bitmap.getWidth();
            height = bitmap.getHeight();
            pixels = new int [width*height];
            bitmap.getPixels(pixels,0,width,0,0,width,height);
        }
    
        public Bitmap getBitmap(){
            return Bitmap.createBitmap(pixels, width, height, Bitmap.Config.ARGB_8888);
        }
    }
  • Now you can use the ProxyBitmap object whenever you want to save Bitmap objects, I wrote a whole example , showing how I save and load serialized ProxyBitmap objects here it is