Android: Convert Drawable to Bitmap
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:
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: