Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert base64 byte array to an image

Tags:

image

jsp

base64

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?

like image 340
SyAu Avatar asked May 09 '12 05:05

SyAu


2 Answers

What you get is just the toString output of an array. You need however the byte array converted to a String.

You should create a method in bean


public String getByteArrayString()
{
   return new String(this.imageByteArray);
}

and reference this in your JSP.

While technically you should define which encoding to use for an array of base64 bytes this is not necessary as all characters are in the standard 7bit ASCII range.

like image 185
DoubleMalt Avatar answered Sep 18 '22 13:09

DoubleMalt


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.

like image 21
Jon Skeet Avatar answered Sep 22 '22 13:09

Jon Skeet