Reputation: 904
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 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 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
"/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"
Upvotes: 3
Views: 3290
Reputation: 8714
In this line
encodedIcon = Base64.encodeToString(iconByteArray, Base64.DEFAULT);
you can change Base64.DEFAULT
to Base64.NOWRAP
It removing \n
from the encoded string.
Upvotes: 0
Reputation: 32576
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 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.
Upvotes: 4