5

I have SVG file encoded as base64, and I want to show the image with ImageView. This is what I tried:

// imageBase64 is string that represents the SVG image encoded as base64    
byte[] decodedString = Base64.decode(imageBase64, Base64.DEFAULT);
Bitmap decodedByte = BitmapFactory.decodeByteArray(decodedString, 0, decodedString.length);

but decodedByte always returned null.

PS:

  • This code works with jpeg images.
  • If the base64 string contains the base64 prefix ("data:image/svg+xml;base64," or "data:image/jpeg;base64,) the decodedByte always returned null too
  • The base64 string is correct (its works good in HTML and other base64 online tools)
v.ladynev
  • 19,275
  • 8
  • 46
  • 67
Bokris Itzhak
  • 911
  • 9
  • 30
  • [Android supports bitmap files in three formats: .png (preferred), .jpg (acceptable), .gif (discouraged).](http://developer.android.com/guide/topics/resources/drawable-resource.html#Bitmap) SVG is a vector format, not a bitmap format. – Robert Longson Dec 30 '15 at 10:27
  • See http://stackoverflow.com/questions/3889882/svg-support-on-android for how to use SVG on Android – Robert Longson Dec 30 '15 at 11:32

1 Answers1

0

(This is based on Robert Longson's insightful comments.)

Your problem is not related to the base64 encoding. It is more fundamental than that.

The approach you are currently taking won't work because BitmapFactory will only decode bitmap file formats. The Bitmap class will only represent PNG, JPG and GIF formats; see the javadoc. (SVG is a vector graphic format not a bitmap format.)

The second issue is that Android does not currently have native support for SVG in ImageView. So you have two alternatives:

  • Display the SVG graphics using an embedded browser window. Android 3+ default browsers support SVG. (Android 2 browsers don't, though there are possible workarounds.)

  • Use a 3rd-party SVG library. There are examples that use a Picture object and others that use a subclass of ImageView. Investigate the options and choose the one that best meets your requirements.

For more details of the alternatives, read the various answers to:

Stephen C
  • 698,415
  • 94
  • 811
  • 1,216