gpt4 book ai didi

java - 从 Android 接收 Base64 编码的字符串到 C# 应用程序

转载 作者:太空狗 更新时间:2023-10-29 12:41:02 28 4
gpt4 key购买 nike

在我的 C# 应用程序中,我将位图编码为从 Android 应用程序发送过来的 base64 字符串,然后对其进行解码并将其设置为字节数组。

不过我得到了这个异常:

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

安卓端:

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# 端:

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

有人知道原因吗?我猜 Java 中 Base64 字符串的格式不能被 C# 应用程序如此简单地解码?看来我可能不得不做 something like this并替换一些字符?我尝试了这个解决方案并得到了同样的异常。

Android发送的字符串是这样的

"/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"

最佳答案

尝试

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);

根据 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.

关于java - 从 Android 接收 Base64 编码的字符串到 C# 应用程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25754469/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com