I am using Android Studio to convert my SVG image to XML file . It works fine when I try to access it using R.drawable.svgimage but now I need to decode that image to bitmap.
I tried the following. It returns null for the bitmap.
mResId = R.drawable.svgimage
BitmapFactory.Options options = new BitmapFactory.Options();
options.inPreferredConfig = Bitmap.Config.ARGB_8888;
Bitmap bitmap = BitmapFactory.decodeResource(
mContext.getResources(), mResId, options);
The following code will works perfectly I have used it:
Here R.drawable.ic_airport
is my svg image stored in drawable folder.
@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);
Log.e(TAG, "getBitmap: 1");
return bitmap;
}
private static Bitmap getBitmap(Context context, int drawableId) {
Log.e(TAG, "getBitmap: 2");
Drawable drawable = ContextCompat.getDrawable(context, drawableId);
if (drawable instanceof BitmapDrawable) {
return BitmapFactory.decodeResource(context.getResources(), drawableId);
} else if (drawable instanceof VectorDrawable) {
return getBitmap((VectorDrawable) drawable);
} else {
throw new IllegalArgumentException("unsupported drawable type");
}
}
Bitmap bitmap = getBitmap(getContext(), R.drawable.ic_airport);
In the package androidx.core.graphics.drawable
there is a function Drawable.toBitmap
val yourBitmap = getDrawable(R.drawable.svgimage)!!.toBitmap(width, height)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With