Getting Bitmap from vector drawable
Asked Answered
B

13

166

In my application, I have to set a large icon for a notification. LargeIcon must be a Bitmap, and my drawables are vector images (the new feature in Android, see this link) The problem is when I try to decode a resource that is a vector image, I get a null returned.

Here is the sample of code :

if (BitmapFactory.decodeResource(arg0.getResources(), R.drawable.vector_menu_objectifs) == null)
        Log.d("ISNULL", "NULL");
    else
        Log.d("ISNULL", "NOT NULL");

In this sample, when I replace R.drawable.vector_menu_objectifs with a "normal" image, a png for exemple, the result is not null (I get the correct bitmap) Is there something I'm missing?

Bradlybradman answered 13/11, 2015 at 15:43 Comment(1)
Had similiar issue, not solution but a workaround: #33548947Backfield
S
284

Checked on API: 17, 21, 23

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

UPDATE:

Project gradle:

dependencies {
        classpath 'com.android.tools.build:gradle:2.2.0-alpha5'
    }

Module gradle:

android {
    compileSdkVersion 23
    buildToolsVersion '23.0.3'
    defaultConfig {
        minSdkVersion 16
        targetSdkVersion 23
        vectorDrawables.useSupportLibrary = true
    }
    ...
}
...
Salvucci answered 7/7, 2016 at 11:29 Comment(7)
AppCompatDrawableManager is marked as @RestrictTo(LIBRARY_GROUP) so it's internal and you should not use it (it's API can change without notice). Use ContextCompat instead.Natal
doesn't work Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.graphics.Bitmap.setHasAlpha(boolean)' on a null object reference on this line Bitmap bitmap = Bitmap.createBitmap(drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight(), Bitmap.Config.ARGB_8888);Oporto
@Natal great, it's working. I've edited the answer to better reflect the best solution.Rambling
I had issues with this solution. For me using: AppCompatResources instead of ContextCompat fixed it: Drawable drawable = AppCompatResources.getDrawable(context, drawableId);Unhandy
This works great for me. Running on API 28 without a problemNutgall
What if the intrinsic dimensions are -1?Turves
There is an extension function in the androidx.core.graphics.drawable package toBitmap()Astraea
P
98

If you are willing to use Android KTX for Kotlin you can use the extension method Drawable#toBitmap() to achieve the same effect as the other answers:

val bitmap = AppCompatResources.getDrawable(requireContext(), drawableId).toBitmap() 

or

val bitmap = AppCompatResources.getDrawable(context, drawableId).toBitmap() 

To add this and other useful extension methods you will need to add the following to your module-level build.gradle

repositories {
    google()
}

dependencies {
    implementation "androidx.core:core-ktx:1.2.0"
}

See here for latest instructions for adding the dependency to your project.

Note that this will work for any subclass of Drawable and if the Drawable is a BitmapDrawable it will shortcut to use the underlying Bitmap.

Pickings answered 8/8, 2018 at 8:35 Comment(3)
This is the most simple solution here for Kotlin.Carnay
For me it works perfectly fine with VectorDrawable.Vertievertiginous
This is best option.. default androidx provides functionalityAmericanist
S
69

You can use the following method:

@TargetApi(Build.VERSION_CODES.LOLLIPOP)
private static Bitmap getBitmap(VectorDrawable vectorDrawable) {
    Bitmap bitmap = Bitmap.createBitmap(vectorDrawable.getIntrinsicWidth(),
            vectorDrawable.getIntrinsicHeight(), Bitmap.Config.ARGB_8888);
    Canvas canvas = new Canvas(bitmap);
    vectorDrawable.setBounds(0, 0, canvas.getWidth(), canvas.getHeight());
    vectorDrawable.draw(canvas);
    return bitmap;
}

which I sometimes combine with:

private static Bitmap getBitmap(Context context, int drawableId) {
    Drawable drawable = ContextCompat.getDrawable(context, drawableId);
    if (drawable instanceof BitmapDrawable) {
        return ((BitmapDrawable) drawable).getBitmap();
    } else if (drawable instanceof VectorDrawable) {
        return getBitmap((VectorDrawable) drawable);
    } else {
        throw new IllegalArgumentException("unsupported drawable type");
    }
}
Swatch answered 11/2, 2016 at 19:8 Comment(3)
hopefully @Bradlybradman comes back and marks this as answer. The one thing to note is that both methods want the targetAPi wrapper — but android studio will tell you that.Destefano
I've spent about two days trying to do this now thinking its svg file issue. Thank you!Evanish
doesn't work Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.graphics.Bitmap.setHasAlpha(boolean)' on a null object reference on this line Bitmap bitmap = Bitmap.createBitmap(vectorDrawable.getIntrinsicWidth(), vectorDrawable.getIntrinsicHeight(), Bitmap.Config.ARGB_8888);Oporto
R
30

Based on the previous answers it can be simplified like that to match both VectorDrawable and BitmapDrawable and to be compatible with at least API 15.

public static Bitmap getBitmapFromDrawable(Context context, @DrawableRes int drawableId) {
    Drawable drawable = AppCompatResources.getDrawable(context, drawableId);

    if (drawable instanceof BitmapDrawable) {
        return ((BitmapDrawable) drawable).getBitmap();
    } else if (drawable instanceof VectorDrawableCompat || drawable instanceof VectorDrawable) {
        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;
    } else {
        throw new IllegalArgumentException("unsupported drawable type");
    }
}

Then you have to add in your gradle file:

android {
    defaultConfig {
        vectorDrawables.useSupportLibrary = true
    }
}

On pre-Lollipop it will use VectorDrawableCompat and on Lollipop it will use VectorDrawable.

EDIT

I've edited the condition following the comment of @user3109468

EDIT 2 (10/2020)

At least from API 21 you can now use this instead of the above code (I haven't tried on previous API versions):

AppCompatResources.getDrawable(context, R.drawable.your_drawable)
Resa answered 28/7, 2016 at 11:53 Comment(2)
drawable instanceof VectorDrawable || drawable instanceof VectorDrawableCompat should have the sides swapped. Results in a Class Not Found when VectorDrawable doesn't exist, when VectorDrawableCompat should be checked first because it does exist.Haggi
type checking of VertorDrawable can be described as (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP && drawable instanceof VectorDrawable)Unapt
G
7

Kudos to @Alexey

Here is the Kotlin version using extensions to Context

fun Context.getBitmapFromVectorDrawable(drawableId: Int): Bitmap? {
    var drawable = ContextCompat.getDrawable(this, drawableId) ?: return null

    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
        drawable = DrawableCompat.wrap(drawable).mutate()
    }

    val bitmap = Bitmap.createBitmap(
            drawable.intrinsicWidth,
            drawable.intrinsicHeight,
            Bitmap.Config.ARGB_8888) ?: return null
    val canvas = Canvas(bitmap)
    drawable.setBounds(0, 0, canvas.width, canvas.height)
    drawable.draw(canvas)

    return bitmap
}

Example usage in Activity:

val bitmap = this.getBitmapFromVectorDrawable(R.drawable.ic_done_white_24dp)
Gyve answered 18/4, 2018 at 14:52 Comment(0)
S
1

Tested on API 16 - JellyBean with Vector Drawables

public static Bitmap getBitmapFromVectorDrawable(Context context, int drawableId) {
    Drawable drawable = AppCompatResources.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;
}   
Shockley answered 28/8, 2019 at 17:39 Comment(0)
D
1

Use the following code to convert image with the correct aspect ratio (e.g., for notification icon):

public static Bitmap getBitmapFromVector(Context context, int drawableId) {
    Drawable drawable = ContextCompat.getDrawable(context, drawableId);
    int width = drawable.getIntrinsicWidth();
    int height = drawable.getIntrinsicHeight();
    Bitmap bitmap;
    if (width < height) {    //make a square
        bitmap = Bitmap.createBitmap(height, height, Bitmap.Config.ARGB_8888);
    } else {
        bitmap = Bitmap.createBitmap(width, width, Bitmap.Config.ARGB_8888);
    }
    Canvas canvas = new Canvas(bitmap);
    drawable.setBounds(0, 0,
            drawable.getIntrinsicWidth(),    //use dimensions of Drawable
            drawable.getIntrinsicHeight()
    );
    drawable.draw(canvas);
    return bitmap;
}
Dysgenic answered 21/2, 2020 at 8:29 Comment(0)
N
1

For the vector drawable here given cup of code help us, but remember it might be null if drawable is not found of NULL

@Nullable
public static Bitmap drawableToBitmap(Context context, int drawableId) {
    Drawable drawable = ContextCompat.getDrawable(context, drawableId);
    if (drawable != null) {
        int width = drawable.getIntrinsicWidth();
        int height = drawable.getIntrinsicHeight();
        Bitmap bmp = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(bmp);
        drawable.setBounds(0, 0, canvas.getWidth(), canvas.getHeight());
        drawable.draw(canvas);
        return bmp;
    }
    return null;
}
Nabalas answered 20/8, 2020 at 10:4 Comment(0)
M
0
Drawable layerDrawable = (Drawable) imageBase.getDrawable();
Bitmap bitmap = Bitmap.createBitmap(layerDrawable.getIntrinsicWidth(),
        layerDrawable.getIntrinsicHeight(), Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
layerDrawable.setBounds(0, 0, canvas.getWidth(), canvas.getHeight());
layerDrawable.draw(canvas);  
imageTeste.setImageBitmap(addGradient(bitmap));
Mclyman answered 3/2, 2018 at 13:28 Comment(0)
H
0

If your vector image intrinsicWidth and intrinsicHeight is small and you try to display the bitmap to a big view, then you will see the result is blur.

In that case, you can provide a new width/height for your bitmap to get the better image (or you can increase the vector size in xml, but provide the desireWidth and desireHeight may be more flexible).

private fun getBitmap(drawableId: Int, desireWidth: Int? = null, desireHeight: Int? = null): Bitmap? {
    val drawable = AppCompatResources.getDrawable(context, drawableId) ?: return null
    val bitmap = Bitmap.createBitmap(
        desireWidth ?: drawable.intrinsicWidth,
        desireHeight ?: drawable.intrinsicHeight,
        Bitmap.Config.ARGB_8888
    )
    val canvas = Canvas(bitmap)
    drawable.setBounds(0, 0, canvas.width, canvas.height)
    drawable.draw(canvas)
    return bitmap
}

Hope it help

Hannahannah answered 29/1, 2019 at 7:1 Comment(0)
G
0

If you want to be able to scale your output to a desired output size, try the following snippet:

fun getBitmapFromVectorDrawable(context: Context, drawableId: Int, outputSize: OutputSize? = null): Bitmap? {
    var drawable = ContextCompat.getDrawable(context, drawableId) ?: return null
    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
        drawable = DrawableCompat.wrap(drawable).mutate()
    }

    var targetBitmap: Bitmap
    if (outputSize != null) {
        targetBitmap = Bitmap.createBitmap(outputSize.width,
                outputSize.height, Bitmap.Config.ARGB_8888)
    } else {
        targetBitmap = Bitmap.createBitmap(drawable.intrinsicWidth,
            drawable.intrinsicHeight, Bitmap.Config.ARGB_8888)
    }

    val canvas = Canvas(targetBitmap)
    val scaleX =  targetBitmap.width.toFloat()/drawable.intrinsicWidth.toFloat()
    val scaleY =  targetBitmap.height.toFloat()/drawable.intrinsicHeight.toFloat()
    canvas.scale(scaleX, scaleY)
    drawable.draw(canvas)

    return targetBitmap
}

class OutputSize(val width: Int, val height: Int)
Ganymede answered 10/4, 2019 at 10:32 Comment(0)
N
0

This gives you the bitmap in the size you want. In addition, it allows you to maintain or not transparency depending on each image for better performance with those that do not need it.

public static Bitmap drawableToBitmap(Resources res, int drawableId,
        int width, int height, boolean keepAlpha) {
    Drawable drawable = res.getDrawable(drawableId);
    Bitmap bmp = createBitmap(width, height, keepAlpha ?
            Bitmap.Config.ARGB_8888 : Bitmap.Config.RGB_565);
    Canvas cvs = new Canvas(bmp);
    drawable.setBounds(0, 0, width, height);
    drawable.draw(cvs);
    return bmp;
}
Nautch answered 3/7, 2020 at 23:46 Comment(0)
A
0

Create separate fun of Vector to Bitmap

 //vectorToBitmapMarker
    private fun fromVectorToBitmap(id: Int, color: Int): BitmapDescriptor
    {
        val vectorDrawable: Drawable? = ResourcesCompat.getDrawable(resources, id, null)

        if (vectorDrawable == null)
        {
            d("VTOB","Resource not found!")
            return BitmapDescriptorFactory.defaultMarker()
        }

        val bitmap = Bitmap.createBitmap(
            vectorDrawable.intrinsicWidth,
            vectorDrawable.intrinsicHeight,
            Bitmap.Config.ARGB_8888)

        val canvas = Canvas(bitmap)
        vectorDrawable.setBounds(0,0,canvas.width, canvas.height)
        DrawableCompat.setTint(vectorDrawable, color)
        vectorDrawable.draw(canvas)

        return BitmapDescriptorFactory.fromBitmap(bitmap)

    }

now do changes in onMapReady() -> .icon()

mMap.addMarker(
       MarkerOptions().position(goa)
           .title("Marker in Goa")
           .draggable(true)
           .icon(fromVectorToBitmap(R.drawable.location, Color.parseColor("#FF0560"))))
Ashore answered 22/7, 2021 at 7:25 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.