Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert a Drawable to a Bitmap?

I would like to set a certain Drawable as the device's wallpaper, but all wallpaper functions accept Bitmaps only. I cannot use WallpaperManager because I'm pre 2.1.

Also, my drawables are downloaded from the web and do not reside in R.drawable.

like image 557
Rob Avatar asked Jun 14 '10 07:06

Rob


People also ask

How do you change a drawable image from a resource to a bitmap?

This example demonstrates how do I convert Drawable to a Bitmap in Android. Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project. Step 2 − Add the following code to res/layout/activity_main. xml.

What is bitmap drawable?

android.graphics.drawable.BitmapDrawable. A Drawable that wraps a bitmap and can be tiled, stretched, or aligned. You can create a BitmapDrawable from a file path, an input stream, through XML inflation, or from a Bitmap object. It can be defined in an XML file with the <bitmap> element.

How do I get bitmap from ImageView?

Bitmap bm=((BitmapDrawable)imageView. getDrawable()). getBitmap(); Try having the image in all drawable qualities folders (drawable-hdpi/drawable-ldpi etc.)


2 Answers

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; } 
like image 38
André Avatar answered Sep 20 '22 13:09

André


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); } 
like image 126
Praveen Avatar answered Sep 21 '22 13:09

Praveen