Convert base64 byte array to image

I have a bean form with id, desc and imageByteArray attributes. The Struts action is executed and redirected to JSP, where I want to access these bean attributes such as id, desc and convert imageByteArray and display it as an image. I tried this post , but it does not work for me.

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

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

I tried this but did not work

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

A byte array (byte [] imageByteArray) refers to a base64 encoded JPG image, and I get the following img output as output, and obviously nothing is displayed,

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

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

+8
jsp image base64
source share
2 answers

What you get is just the output of the toString of the array. However, you need an array of bytes converted to a string.

You must create a method in a bean

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

and indicate this in your JSP.

While technically you have to determine which encoding to use for the base64 byte array, this is not necessary, since all characters are in the standard 7-bit ASCII range.

+11
source share

DoubleMalt's answer (accepted at the time of writing) is unsuccessful because it uses two violations to do the right thing. This does not help the Apache Commons Codec make it so easy to do the wrong thing :(

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

Now you can choose exactly when you convert to base64 (and string). You can do this earlier in your Java code, in which case I would 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 can only store binary data in a bean and encode in JSP. I haven't written JSP for a long time, so I'm not going to write code for this here.

But basically, you need to decide whether your bean should store the original binary data as byte[] , or the data with the underlying 64 code as String . Everything else is misleading, IMO.

+3
source share

All Articles