Convert base64 byte array to an image - 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?

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.

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.

Related

How to decode base64 & hexadecimal response from query

The query comes as
"returnData": [
"zWCLtKpUXZbkWNM9deAVPizTxXASOjX63ubdUHDN+vw=",
"zWCLtKpUXZbkWNM9deAVPizTxXASOjX63ubdUHDN+vw="
],
How can I decode that string? I can see it is decodable base64 first, but I get a very weird string after. Can someone show me the steps to follow to receive the decoded final string?
Base64 encodes binary data, which means if you send data that is not a string you won't be able to retrieve a string back. So to properly parse the return data you will need to know what data types were actually returned.
It might also be helpful to use a base64 to hex decoder first, so you get the hex representation of your data.
To give you more concrete recommendations we would need to know what data you expected, preferably showing the whole endpoint definition as well as any custom structs that might be involved.

CapnProto encodes string twice

I have a simple struct containing some stuff, and also a Text field. I was looking at the result of encoding this data using Capnp, and for some reason the value of the text field appears in the encoded output twice! That doesn't seem very efficient or sane. Why does this happen?
Cap'n Proto does not encode text fields twice. To understand what happened in your case, we'd need to see your code.

How to avoid exception by mapping string to number in thymeleaf?

I have some HTML page and on this page I will provide the possibility for free text.
For example, it is possible to write in textbox either: 10 or 10 apples.
In a case of writing 10 apples I got NumberFormatException which is correct, but for me will be good to extract only number automatically without javascript writing.
Is it possible to map string from HTML page to the number in my java entity? May be with some annotation or somehow else?
Try:
final String stripped = textbox.getText().replaceAll("[^0-9]", "");
This takes the contents of the text field and strips out any characters that aren't digits. If you need to deal with floating point or negative numbers, it can be done, but becomes more complicated.

Catch 22 of Cocoa URL encoding

After checking how others try to do URL encoding in Cocoa (like How do I URL encode a string, Swift - encode URL, etc.) I still have no clue how to correctly URL encode in Cocoa if
URLs come from externally therefore their structure (parts) not known ahead
can be encoded or pure URL strings
BONUS can be relative and local file URLs
I do not want to encode blindly always all the characters but according to rfc3986 (rfc2396, rfc1738, rfc1808)
The catch 22:
stringByAddingPercentEscapesUsingEncoding: converts lazily so the preferred method would be using stringByAddingPercentEncodingWithAllowedCharacters: for each url components one by one
[NSURL URLWithString:], [NSURLComponents componentsWithString:] and companions will fail if the incoming string is not (at least partially) encoded, but if I pass a stringByAddingPercentEscapesUsingEncoding: encoded string than the component splitting will fail (f.e. the encoded # will confuse the splitter and the fragment will be treated the part of a possible query section
How to URL encode correctly in this case without writing my own URL parser, encoder?
You should read all of Apple's release note discussion of this subject, but in particular this part may be most relevant for your case:
If you need to percent-encode an entire URL string, you can use this
code to encode a NSString intended to be a URL (in urlStringToEncode):
NSString *percentEncodedURLString =
[[NSURL URLWithDataRepresentation:[urlStringToEncode dataUsingEncoding:NSUTF8StringEncoding] relativeToURL:nil] relativeString];
(The CoreFoundation equivalent to URLWithDataRepresentation: is
CFURLCreateWithBytes() using the encoding kCFStringEncodingUTF8 with a
fall back to kCFStringEncodingISOLatin1 if kCFStringEncodingUTF8
fails.)
Basically, +URLWithDataRepresentation:relativeToURL: does its best to make a proper URL from the provided bytes. Given that you can't guarantee almost anything about the input, there can't be any promises that it will get it "right" (because "right" isn't well defined in that case), but it's probably your best hope.

Convert to unicode from UTF-8 [duplicate]

I try to convert a UTF8 string to a Java Unicode string.
String question = request.getParameter("searchWord");
byte[] bytes = question.getBytes();
question = new String(bytes, "UTF-8");
The input are Chinese Characters and when I compare the hex code of each caracter it is the same Chinses character. So I'm pretty sure that the charset is UTF8.
Where do I go wrong?
There's no such thing as a "UTF-8 string" in Java. Everything is in Unicode.
When you call String.getBytes() without specifying an encoding, that uses the platform default encoding - that's almost always a bad idea.
You shouldn't have to do anything to get the right characters here - the request should be handling it all for you. If it's not doing so, then chances are it's lost data already.
Could you give an example of what's actually going wrong? Specify the Unicode values of the characters in the string you're receiving (e.g. by using toCharArray() and then converting each char to an int) and what you expected to receive.
EDIT: To diagnose this, use something like this:
public static void dumpString(String text) {
for (int i = 0; i < text.length(); i++) {
System.out.println(i + ": " + (int) text.charAt(i));
}
}
Note that that will give the decimal value of each Unicode character. If you have a handy hex library method around, you may want to use that to give you the hex value. The main point is that it will dump the Unicode characters in the string.
First make sure that the data is actually encoded as UTF-8.
There are some inconsistency between browsers regarding the encoding used when sending HTML form data. The safest way to send UTF-8 encoded data from a web form is to put that form on a page that is served with the Content-Type: text/html; charset=utf-8 header or contains a <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> meta tag.
Now to properly decode the data call request.setCharacterEncoding("UTF-8") in your servlet before the first call to request.getParameter().
The servlet container takes care of the encoding for you. If you use setCharacterEncoding() properly you can expect getParameter() to return normal Java strings.
Also you may need a special filter which will take care of encoding of your requests. For example such filter exists in spring framework org.springframework.web.filter.CharacterEncodingFilter
String question = request.getParameter("searchWord");
is all you have to do in your servlet code. At this point you have not to deal with encodings, charsets etc. This is all handled by the servlet-infrastucture. When you notice problems like displaying �, ?, ü somewhere, there is maybe something wrong with request the client sent. But without knowing something of the infrastructure or the logged HTTP-traffic, it is hard to tell what is wrong.
possibly.
question = new String(bytes, "UNICODE");

Resources