Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Decoding bitmap from Drawable Resource Id is giving null

I want to get Bitmap from drawable resource id, I found a solution to decode it using BitmapFactory decode method, but it's giving null.

Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.ic_tick);
like image 865
Marium Jawed Avatar asked Aug 23 '19 12:08

Marium Jawed


1 Answers

Please check if you are using Vector drawable or normal png/jpeg image as a drawable, it gives null value if you try to decode vector drawable.

Use this code if you are trying to decode Vector drawable

public static Bitmap getBitmapFromVectorDrawable(Context context, int drawableId) {
Drawable drawable = ContextCompat.getDrawable(context, drawableId);
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
    drawable = (DrawableCompat.wrap(drawable)).mutate();
}

Bitmap 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;
}

Also make sure if you have vector support enable in your app gradle

vectorDrawables.useSupportLibrary = true
like image 102
Hamza Khan Avatar answered Oct 11 '22 21:10

Hamza Khan