Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Decoding SVG image to bitmap

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); 
like image 647
Siju Avatar asked Sep 22 '15 12:09

Siju


2 Answers

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);
like image 124
Harsh Mittal Avatar answered Nov 06 '22 01:11

Harsh Mittal


In the package androidx.core.graphics.drawable there is a function Drawable.toBitmap

val yourBitmap = getDrawable(R.drawable.svgimage)!!.toBitmap(width, height)
like image 10
Benjamin Basmaci Avatar answered Nov 06 '22 00:11

Benjamin Basmaci