Drawable to Bitmap (and vice versa)

Drawable to Bitmap (and vice versa)

This code convert a Bitmap to Drawable and vice versa. It is useful when we are working with graphics.

// YourActivity.java

private Bitmap drawableToBitmap(Drawable drawable) {
  if (drawable == null) {
    return null;
  }

  return ((BitmapDrawable)drawable).getBitmap();
}

private Drawable bitmapToDrawable(Bitmap bitmap) {
  if (bitmap == null) {
    return null;
  }
  
  return new BitmapDrawable(bitmap);
}