Convert base64 byte array to an image

I have a form bean with attributes id, desc and imageByteArray. Struts action gets executed and it redirects to a JSP where i want to access these bean attributes like id, desc and convert the imageByteArray and display it as an image. I tried this post, but that's not working for me.

I encode the bytearray using Base64 - where this.bean.imageByteArray refers to the form bean

this.bean.setImageByteArray(new org.apache.commons.codec.binary.Base64().encode(imageInByteArr));

I tried this, but not working

<img src="data:image/jpg;base64,<c:out value='${bean.imageByteArray}'/>" />

Byte array (byte[] imageByteArray) refers a base64 encoded JPG image and I'm getting the following img tag as output and obviously nothing gets displayed,

<img src="data:image/jpg;base64,[B@2e200e">

Any idea how to convert base64 byte array and display as an image in JSP?

Jon Skeet
people
quotationmark

DoubleMalt's answer (accepted at the time of writing) is unfortunate, because it's sort of using two wrongs to make a right. It doesn't help that Apache Commons Codec makes it so easy to do the wrong thing :(

Base64 is fundamentally an encoding from binary data to text - as such, it should almost always be used to convert a byte[] to a String. Your issue is that you're converting a byte[] to another byte[] - but you later want to use that data as a string. It would be better to convert once, in the right way.

Now you can choose exactly when you convert to base64 (and a string). You could do it early, in your Java code, in which case I'd use:

// Obviously you'd need to introduce a new method for this, replacing
// setImageByteArray
this.bean.setImageBase64(new Base64().encodeToString(imageInByteArr));
<img src="data:image/jpg;base64,<c:out value='${bean.imageBase64}'/>" />

Alternatively, you could keep just the binary data in your bean, and the perform the encoding in the JSP. It's been a long time since I've written any JSPs, so I'm not going to try to write the code for that here.

But basically, you need to decide whether your bean should keep the original binary data as a byte[], or the base64-encoded data as a String. Anything else is misleading, IMO.

people

See more on this question at Stackoverflow