parameter parameter - 5 months ago 37x
Android Question

Receiving a Base64 encoded string from Android into C# application

In my C# application, I am having a Bitmap encoded to a base64 string sent over from an android application, then I decode it and set it equal to a byte array.

I get this exception though:

"A first chance exception of type 'System.FormatException' occurred in

Android Side:

byte[] iconByteArray = null;
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 90, baos); //Bitmap bitmap created elsewhere
iconByteArray = baos.toByteArray();
encodedIcon = Base64.encodeToString(iconByteArray, Base64.DEFAULT);
return encodedIcon;

C# Side:

byte[] arr = System.Convert.FromBase64String(encodedIcon); //this throws that exception

Does anyone know of the cause? I'm guessing the format of the Base64 string in Java is not able to be decoded so simply by the C# application? It looks like I may have to do something like this and replace some characters? I tried this solution and got the same exception.

The string sent through Android looks like this




encodedIcon = encodedIcon.Replace(@"\n", "");
if(encodedIcon.Length % 4 != 0)
    // we may have 0, 1 or 2 padding '='
    encodedIcon += new string('=', 4 - encodedIcon.Length % 4);
byte[] arr = System.Convert.FromBase64String(encodedIcon);

According to Base64:

After encoding the non-padded data, if two octets of the 24-bit buffer are padded-zeros, two "=" characters are appended to the output; if one octet of the 24-bit buffer is filled with padded-zeros, one "=" character is appended. This signals the decoder that the zero bits added due to padding should be excluded from the reconstructed data. This also guarantees that the encoded output length is a multiple of 4 bytes.