Drawable to Bitmap
It is easy to convert between Drawable and Bitmap in Android.
Bitmap icon = BitmapFactory.decodeResource(context.getResources(), R.drawable.icon_resource);
Above works for jpg, png type drawables, but it does work for xml type of drawable (I guess because xml file has no specific “width”, “height” information).
In this case, you can use following util method.
public static Bitmap drawableToBitmap (Drawable drawable) { Bitmap bitmap = null; if (drawable instanceof BitmapDrawable) { BitmapDrawable bitmapDrawable = (BitmapDrawable) drawable; if(bitmapDrawable.getBitmap() != null) { return bitmapDrawable.getBitmap(); } } if(drawable.getIntrinsicWidth() <= 0 || drawable.getIntrinsicHeight() <= 0) { bitmap = Bitmap.createBitmap(1, 1, Bitmap.Config.ARGB_8888); // Single color bitmap will be created of 1x1 pixel } else { bitmap = Bitmap.createBitmap(drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight(), Bitmap.Config.ARGB_8888); } Canvas canvas = new Canvas(bitmap); drawable.setBounds(0, 0, canvas.getWidth(), canvas.getHeight()); drawable.draw(canvas); return bitmap; }
Above is cited from How to convert a Drawable to a Bitmap? answered by André.
Bitmap to Drawable
Drawable d = new BitmapDrawable(getResources(), bitmap);
Bitmap to Drawable
private static final int IMAGE_WIDTH = 320; private static final int IMAGE_HEIGHT = 180; Bitmap scaledBitmap = Bitmap.createScaledBitmap(bitmap, IMAGE_WIDTH, IMAGE_HEIGHT, true);
A
Drawable
that wraps a bitmap and can be tiled, stretched, or aligned. You can create aBitmapDrawable
from a file path, an input stream, through XML inflation, or from aBitmap
object.