Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert byte[] to Base64 string for data URI

I know this has probably been asked 10000 times, however, I can't seem to find a straight answer to the question.

I have a LOB stored in my db that represents an image; I am getting that image from the DB and I would like to show it on a web page via the HTML IMG tag. This isn't my preferred solution, but it's a stop-gap implementation until I can find a better solution.

I'm trying to convert the byte[] to Base64 using the Apache Commons Codec in the following way:

String base64String = Base64.encodeBase64String({my byte[]}); 

Then, I am trying to show my image on my page like this:

<img src="data:image/jpg;base64,{base64String from above}"/> 

It's displaying the browser's default "I cannot find this image", image.

Does anyone have any ideas?

Thanks.

like image 347
El Guapo Avatar asked Jan 29 '11 17:01

El Guapo


1 Answers

I used this and it worked fine (contrary to the accepted answer, which uses a format not recommended for this scenario):

StringBuilder sb = new StringBuilder(); sb.append("data:image/png;base64,"); sb.append(StringUtils.newStringUtf8(Base64.encodeBase64(imageByteArray, false))); contourChart = sb.toString(); 
like image 55
WhyNotHugo Avatar answered Sep 19 '22 00:09

WhyNotHugo