Search code examples
javahtmlimagebase64data-uri

Generate base64 string of an image to use in data URI


How to generate base64 string of an image to use in data URI?

I have an Base64 image encoding issue that I hope someone can help with. I'm trying to use data uri in my web page (ie <img src="data:image/png;base64,iVBORw..."/> with org.apache.commons.codec.binary.Base64 v1.8 generating the base64 string of png image.

To generate the base64 string I have used:

Base64.encodeBase64URLSafeString(imageFile)

The problem is the browser cannot render the image. I compared this generated string with one that works and I noticed the differences are the Apache Base64 version has "_" and "-" characters instead of "/" and "+". From the internet I see there are different Base64 formats so I assume Apache's implementation is not compatible with the browsers.

So I was wondering is there a library that implements the base64 format that would be appropriate for my purposes? My current fix is to just replace the characters but I would rather use a library.


Solution

  • According to the javadoc of the Base64.encodeBase64URLSafeString method, that seems to be by design. Check out the link I provided, it says this in the javadoc:

    Encodes binary data using a URL-safe variation of the base64 algorithm but does not chunk the output. The url-safe variation emits - and _ instead of + and / characters. Note: no padding is added.

    So you want to make sure you use the url-unsafe variation. That's the method called encodeBase64. Use this method instead:

    Base64.encodeBase64(imageFile)