SVG decoding for a bitmap

I am using Android Studio to convert an SVG image to an XML file. It works great when I try to access it using R.drawable.svgimage, but now I need to decode this image for a 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); 
+6
source share
3 answers

The following code works fine, I used it: Here R.drawable.ic_airport is my svg image stored in a transferable 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); 
+3
source

You can use this Android SVG library and use it as follows:

 SVG svg = new SVGBuilder() .readFromResource(getResources(), R.raw.someSvgResource) // if svg in res/raw .readFromAsset(getAssets(), "somePicture.svg") // if svg in assets // .setWhiteMode(true) // draw fills in white, doesn't draw strokes // .setColorSwap(0xFF008800, 0xFF33AAFF) // swap a single colour // .setColorFilter(filter) // run through a colour filter // .set[Stroke|Fill]ColorFilter(filter) // apply a colour filter to only the stroke or fill .build(); 

After that, convert the SVG to Drawable:

 // Draw onto a canvas canvas.drawPicture(svg.getPicture()); // Turn into a drawable Drawable drawable = svg.createDrawable(); 

and then output to a bitmap:

 Bitmap bitmapsvg = BitmapFactory.decodeResource(context.getResources(),drawable); 
+2
source

try it,

 SVG svg = SVGParser.getSVGFromResource(getResources(), R.raw.android); PictureDrawable pictureDrawable = svg.createPictureDrawable(); Bitmap bitmap = Bitmap.createBitmap(pictureDrawable.getIntrinsicWidth(), pictureDrawable.getIntrinsicHeight(), Config.ARGB_8888); 
+1
source

All Articles