Android How to - Convert Drawable to Bitmap








Question

We would like to know how to convert Drawable to Bitmap.

Answer

The following method shows how to create a Bitmap from a drawable object.

A Canvas is created to wrap the Bitmap and drawable object can paint to the Canvas. In this way we can create a Bitmap from a Drawable object.

//  w w w.  j a  v a 2s. co m
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.PixelFormat;
import android.graphics.drawable.Drawable;
public class Main {
    public static Bitmap drawableToBitmap(Drawable drawable) {
    Bitmap bitmap = Bitmap.createBitmap(drawable.getIntrinsicWidth(),drawable.getIntrinsicHeight(),
    drawable.getOpacity() != PixelFormat.OPAQUE ? Bitmap.Config.ARGB_8888: Bitmap.Config.RGB_565);
    Canvas canvas = new Canvas(bitmap);
    drawable.setBounds(0, 0, drawable.getIntrinsicWidth(),drawable.getIntrinsicHeight());
    drawable.draw(canvas);
  return bitmap;
    }
}