Andrew Andrew - 10 days ago 6
JSON Question

Sending base64-encoded image results in a corrupt image

I'm encoding an image with

Base64.encodeToString
, adding it (among other pieces of data) to a JSON body and sending it to a web service for storage.

My encoding method looks like this:

private static String encodeToBase64(Bitmap image) {
Bitmap immagex = image;
ByteArrayOutputStream baos = new ByteArrayOutputStream();
immagex.compress(Bitmap.CompressFormat.JPEG, 100, baos);
byte[] bytes = baos.toByteArray();
String imageEncoded = Base64.encodeToString(bytes, Base64.DEFAULT);
return imageEncoded;
}


I then simply call
.add("encoded_image", encodeToBase64(bitImage));
on the
JSONObject
and send it through my web service class.

However, when I get the image on the other side, it is corrupt. The PHP function
base64_decode
executes and seems to provide an image, but when I write that image to a temp file, I cannot open it. It says the image is corrupt. I'm not really sure where to start looking.

I've looked at other threads, but their solutions don't seem to work.

Help is appreciated. Thanks.

Answer

I don't think that the DEFAULT options mix well with your PHP version. There appears to be a bug in certain versions on PHP which makes the base64_decode bug out if the input is not properly formatted.

Try adding the NO_WRAP option, to make sure that there are no whitespace/likebreak characters in the produced output.

If that does not help, have a look at the manual page for the base64_decode function for hints on how to get it working.

It might also help if you analysed what you send in android and receive in php, i.e. log some debug output or inspect with breakpoints, to see if anything is wrong.

Comments