Home » Android » android – How to set a bitmap from resource

android – How to set a bitmap from resource

Posted by: admin March 10, 2020 Leave a comment


This seems simple, I am trying to set a bitmap image but from the resources, I have within the application in the drawable folder.

bm = BitmapFactory.decodeResource(null, R.id.image);

Is this correct?

How to&Answers:

Assuming you are calling this in an Activity class

Bitmap bm = BitmapFactory.decodeResource(getResources(), R.drawable.image);

The first parameter, Resources, is required. It is normally obtainable in any Context (and subclasses like Activity).


Try this

This is from sdcard

ImageView image = (ImageView) findViewById(R.id.test_image);
Bitmap bMap = BitmapFactory.decodeFile("/sdcard/test2.png");

This is from resources

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


If the resource is showing and is a view, you can also capture it. Like a screenshot:

View rootView = ((View) findViewById(R.id.yourView)).getRootView();
rootView.layout(0, 0, rootView.getWidth(), rootView.getHeight());

Bitmap bm = Bitmap.createBitmap(rootView.getDrawingCache());


This actually grabs the whole layout but you can alter as you wish.


If you have declare a bitmap object and you want to display it or store this bitmap object. but first you have to assign any image , and you may use the button click event, this code will only demonstrate that how to store the drawable image in bitmap Object.

Bitmap contact_pic = BitmapFactory.decodeResource(

Now you can use this bitmap object, whether you want to store it, or to use it in google maps while drawing a pic on fixed latitude and longitude, or to use some where else


just replace this line

bm = BitmapFactory.decodeResource(null, R.id.image);


Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.YourImageName);

I mean to say just change null value with getResources() If you use this code in any button or Image view click event just append getApplicationContext() before getResources()..