title: Serializing and De-Serializing android.graphics.Bitmap in Java
body: <p>I have started work on an my first android application and have the basis of an application that handles an image with multiple layers. I am able to export a flat version of the project file as a PNG but I would like to be able to save the layered image for later editing (including any options applied to certain layers, such as text based layers).</p>
  
  <p>Anyway, I have ensured that the classes that need to be written to a file are 'Serializable' but have run into a bit of a road block caused by the fact that android.graphics.Bitmap isn't serializable. The following code essentially outputs the Bitmap as a PNG into a ByteArray and should read it back in as part of 'readObject'. However, when the code runs - I can verify that the 'imageByteArrayLength' variable that is read in is the same as that which is output - but the 'Bitmap image' is always null.</p>
  
  <p>Any help would be greatly appreciated. Thanks for reading.</p>
  
  <pre><code>private String title;
  private int width;
  private int height;
  private Bitmap sourceImage;
  private Canvas sourceCanvas;        
  private Bitmap currentImage;
  private Canvas currentCanvas;   
  private Paint currentPaint; 
  
  private void writeObject(ObjectOutputStream out) throws IOException{
      out.writeObject(title);
      out.writeInt(width);
      out.writeInt(height);
  
      ByteArrayOutputStream stream = new ByteArrayOutputStream();
      currentImage.compress(Bitmap.CompressFormat.PNG, 100, stream);
      byte[] imageByteArray = stream.toByteArray();
  
      int length = imageByteArray.length;
      out.writeInt(length);
      out.write(imageByteArray);          
  }
  
  private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException{
      this.title = (String)in.readObject();
      this.width = in.readInt();
      this.height = in.readInt();
  
      int imageByteArrayLength = in.readInt();
      byte[] imageByteArray = new byte[imageByteArrayLength];
      in.read(imageByteArray, 0, imageByteArrayLength);
  
      BitmapFactory.Options opt = new BitmapFactory.Options();
      opt.inPreferredConfig = Bitmap.Config.ARGB_8888;
  
      Bitmap image = BitmapFactory.decodeByteArray(imageByteArray, 0, imageByteArrayLength, opt);
  
      sourceImage = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
      currentImage = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
  
      sourceCanvas = new Canvas(sourceImage);
      currentCanvas = new Canvas(currentImage);
      currentPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
  
      if ( image != null ) {
          sourceCanvas.drawBitmap(image, 0, 0, currentPaint);
      }
  }   
  </code></pre>