Signup/Sign In
Ask Question
Not satisfied by the Answer? Still looking for a better solution?

How to convert a Drawable to a Bitmap?

I might want to set a specific Drawable as the gadget's wallpaper, however, all wallpaper capacities acknowledge Bitmaps as it were. I can't utilize WallpaperManager on the grounds that I'm pre 2.1.

Additionally, my drawables are downloaded from the web and don't live in R.drawable.
by

2 Answers

rahul07
This piece of code helps.

Bitmap icon = BitmapFactory.decodeResource(context.getResources(),
R.drawable.icon_resource);

Here a version where the image gets downloaded.

String name = c.getString(str_url);
URL url_value = new URL(name);
ImageView profile = (ImageView)v.findViewById(R.id.vdo_icon);
if (profile != null) {
Bitmap mIcon1 =
BitmapFactory.decodeStream(url_value.openConnection().getInputStream());
profile.setImageBitmap(mIcon1);
}
kshitijrana14
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;
}

Login / Signup to Answer the Question.