Andrew Andrew - 1 year ago 88
JSON Question

Sending base64-encoded image results in a corrupt image

I'm encoding an image with

, 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
and send it through my web service class.

However, when I get the image on the other side, it is corrupt. The PHP function
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 Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download