Android: Convert Drawable to Bitmap

Mike Solomon

Recently when working on an Android app I needed to convert a Drawable object to a Bitmap object. Rasterizing a Drawable is actually pretty easy if you use this method:

public Bitmap convertToBitmap(Drawable drawable, int widthPixels, int heightPixels) {
    Bitmap mutableBitmap = Bitmap.createBitmap(widthPixels, heightPixels, Bitmap.Config.ARGB_8888);
    Canvas canvas = new Canvas(mutableBitmap);
    drawable.setBounds(0, 0, widthPixels, heightPixels);
    drawable.draw(canvas);

    return mutableBitmap;
}

First we create a mutable Bitmap object of the correct size in pixels. I recommend you use ARGB_8888 instead of another Bitmap configuration unless you have a specific reason not to.

Then we create a new Canvas backed by that bitmap, set the bounds appropriately on the drawable, and draw the Drawable onto the Canvas. This is when the Drawable actually gets mapped onto the pixels represented by the Bitmap.

We now have a Bitmap suitable for use elsewhere. I have found this to be a useful technique for masking images with Path objects when antialiasing is required.

Write Bitmap as a JPEG image

If you want to write a Bitmap (or a Drawable that has been converted to a Bitmap) as a JPEG image, you can use this simple technique:

public void writeJpegImageToFile(Bitmap bitmap, FileOutputStream jpegFileStream) {
    // use JPEG quality of 80 (scale 1 - 100)
    bitmap.compress(Bitmap.CompressFormat.JPEG, 80, jpegFileStream);
}
comments powered by Disqus