Decoding bitmap from Drawable Resource Id is giving null

Marium Jawed :

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);
Hamza Khan :

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

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=138886&siteId=1