I would like to set a certain Drawable
as the device\'s wallpaper, but all wallpaper functions accept Bitmap
s only. I cannot use WallpaperMan
The latest androidx core library (androidx.core:core-ktx:1.2.0) now has an extension function: Drawable.toBitmap(...) to convert a Drawable to a Bitmap.
METHOD 1 : Either you can directly convert to bitmap like this
Bitmap myLogo = BitmapFactory.decodeResource(context.getResources(), R.drawable.my_drawable);
METHOD 2 : You can even convert the resource into the drawable and from that you can get bitmap like this
Bitmap myLogo = ((BitmapDrawable)getResources().getDrawable(R.drawable.logo)).getBitmap();
For API > 22 getDrawable
method moved to the ResourcesCompat
class so for that you do something like this
Bitmap myLogo = ((BitmapDrawable) ResourcesCompat.getDrawable(context.getResources(), R.drawable.logo, null)).getBitmap();
Android provides a non straight foward solution: BitmapDrawable
. To get the Bitmap , we'll have to provide the resource id R.drawable.flower_pic
to the a BitmapDrawable
and then cast it to a Bitmap
.
Bitmap bm = ((BitmapDrawable) getResources().getDrawable(R.drawable.flower_pic)).getBitmap();
if you are using kotlin the use below code. it'll work
// for using image path
val image = Drawable.createFromPath(path)
val bitmap = (image as BitmapDrawable).bitmap
very simple
Bitmap tempBMP = BitmapFactory.decodeResource(getResources(),R.drawable.image);
BitmapFactory.decodeResource()
automatically scales the bitmap, so your bitmap may turn out fuzzy. To prevent scaling, do this:
BitmapFactory.Options options = new BitmapFactory.Options();
options.inScaled = false;
Bitmap source = BitmapFactory.decodeResource(context.getResources(),
R.drawable.resource_name, options);
or
InputStream is = context.getResources().openRawResource(R.drawable.resource_name)
bitmap = BitmapFactory.decodeStream(is);