mattfred mattfred - 6 months ago 63
Android Question

SVG data URI to bitmap

I have a SVG byte array that I need to convert to an image in Android. The byte array is encoded using Base64. I believe that Android does not support SVG images, which is causes my conversion method to return a null. Is there anyway this can be done?

Here is the method I was trying to use to convert the image:

public static Bitmap imageFromString(String imageData) {
String data = imageData.substring(imageData.indexOf(",") + 1);
byte[] imageAsBytes = Base64.decode(data.getBytes(), Base64.DEFAULT);
return BitmapFactory.decodeByteArray(imageAsBytes, 0, imageAsBytes.length);
}

Answer

Using AndroidSVG, you would need to do something like the following:

public static Bitmap imageFromString(String imageData)
{
  String data = imageData.substring(imageData.indexOf(",") + 1);
  byte[] imageAsBytes = Base64.decode(data.getBytes(), Base64.DEFAULT);
  String  svgAsString = new String(imageAsBytes, StandardCharsets.UTF_8);

  SVG  svg = SVG.getFromString(svgAsString);

  // Create a bitmap and canvas to draw onto
  float   svgWidth = (svg.getDocumentWidth() != -1) ? svg.getDocumentWidth() : 500f;
  float   svgHeight = (svg.getDocumentHeight() != -1) ? svg.getDocumentHeight() : 500f;

  Bitmap  newBM = Bitmap.createBitmap(Math.ceil(svgWidth),
                                      Math.ceil(svgHeight),
                                      Bitmap.Config.ARGB_8888);
  Canvas  bmcanvas = new Canvas(newBM);

  // Clear background to white if you want
  bmcanvas.drawRGB(255, 255, 255);

  // Render our document onto our canvas
  svg.renderToCanvas(bmcanvas);

  return newBM;
}
Comments