Getting Base64 encoded string from Android into C # app
In my C # application, I have a base64 encoded bitmap passed from android application, then I decode it and set it equal to byte array.
I am getting this exception:
"The first exception of type 'System.FormatException' occurred in mscorlib.dll."
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 the reason? I'm guessing the Base64 string format in Java cannot be decoded so easily by a C # application? It looks like I might have to do something like this and replace some characters? I tried this solution and got the same exception.
The string sent via Android looks like this
"/ 9J / 4AAQSkZJRgABAQAAAQABAAD / 2wBDAAMCAgMCAgMDAwMEAwMEBQgFBQQEBQoHBwYIDAoMDAsK \ nCwsNDhIQDQ4RDgsLEBYQERMUFRUVDA8XGBYUGBIUFRT / 2wBDAQMEBAUEBQkFBQkUDQsNFBQUFBQU \ nFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBT / wAARCABgAGADASIA \ nAhEBAxEB / 8QAHwAAAQUBAQEBAQEAAAAAAAAAAAECAwQFBgcICQoL / 8QAtRAAAgEDAwIEAwUFBAQA \ nAAF9AQIDAAQRBRIhMUEGE1FhByJxFDKBkaEII0KxwRVS0fAkM2JyggkKFhcYGRolJicoKSo0NTY3 \ nODk6Q0RFRkdISUpTVFVWV1hZWmNkZWZnaGlqc3R1dnd4eXqDhIWGh4iJipKTlJWWl5iZmqKjpKWm \ np6ipqrKztLW2t7i5usLDxMXGx8jJytLT1NXW19jZ2uHi4 + Tl5ufo6erx8vP09fb3 + PN6 / 8QAHwEA \ nAwEBAQEBAQEBAQAAAAAAAAECAwQFBgcICQoL / 8QAtREAAgECBAQDBAcFBAQAAQJ3AAECAxEEBSEx \ nBhJBUQdhcRMiMoEIFEKRobHBCSMzUvAVYnLRChYkNOEl8RcYGRomJygpKjU2Nzg5OkNERUZHSElK \ nU1RVVldYWVpjZGVmZ2hpanN0dXZ3eHl6goOEhYaHiImKkpOUlZaXmJmaoqOkpaanqKmqsrO0tba3 \ nuLm6wsPExcbHyMnK0tPU1dbX2Nna4uPk5ebn6Onq8vP09fb3 +PN6 / 9oADAMBAAIRAxEAPwD8qq2t \ nG8EeIvENqbrStC1PUrYMUM1pZyyoGHUZVSM8jj3rFr9av2Ipl + Gf7PHh + xn1qfzNQL6rttY5AsYm \ nCsEPzDJAHJx3roo4atiW1QjzNHBi8fhcBFSxU + VPRaN / kmfl9 / wqrxp / 0KWu / WDgsn / + Io / 4VV40 \ n / wChS13 / AMFk / wD8RX7cj4m "
source to share
Try
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 non-overflow data is encoded, if two octets of the 24-bit buffer are filled with zeros, two "=" characters are appended to the output; if one octet of the 24-bit buffer is filled with padded zeros, one "=" is appended. This signals to the decoder that the padded zero bits should be excluded from the recovered data. It also ensures that the encoded output length is a multiple of 4 bytes.
source to share