[英]FormatException when converting Base64 string to bytes
I am getting an exception when trying to convert a base64 string to a byte array. 尝试将base64字符串转换为字节数组时出现异常。 I am converting an Image to a byte array then to a base64 string, then encrypting it and storing it in a file.
我将图像转换为字节数组,然后转换为base64字符串,然后对其进行加密并将其存储在文件中。 Then I am attempting to convert the base64 string back to a byte array in a MemoryStream, and recreating the image.
然后,我尝试将base64字符串转换回MemoryStream中的字节数组,然后重新创建图像。 I am getting a FormatException here:
我在这里收到FormatException:
byte[] imgBytes = Convert.FromBase64String(str);
Here is the full code for the two main functions: 这是两个主要功能的完整代码:
public string ImageToString(Image img)
{
using (MemoryStream ms = new MemoryStream())
{
img.Save(ms, ImageFormat.Jpeg);
return Convert.ToBase64String(ms.ToArray());
}
}
public Image StringToImage(String str)
{
int lent = str.Length;
byte[] imgBytes = Convert.FromBase64String(str);
MemoryStream ms = new MemoryStream(imgBytes, 0, imgBytes.Length);
ms.Write(imgBytes, 0, imgBytes.Length);
return Image.FromStream(ms, true);
}
Here is the beginning and end of the base64 string I am trying to convert.... G>/9j/4AAQSkZJRgABAQEAYABgAAD .... Uh+8fxpT/B9KAP/2Q==
这是我要转换的base64字符串的开头和结尾。...
G>/9j/4AAQSkZJRgABAQEAYABgAAD .... Uh+8fxpT/B9KAP/2Q==
Any ideas are greatly appreciated! 任何想法都将不胜感激!
The problem is that your string got corrupted somewhere along the line. 问题是您的字符串沿行的某个位置损坏了。 That's not a base64 string, as you can see by the second charcter
>
, which does not occur in a base64 string. 这不是base64字符串,如第二个charcter
>
,它不是在base64字符串中出现的。
Side note: Your function creates a memory stream containing the data, then writes the data to the memory stream again. 旁注:函数将创建一个包含数据的存储流,然后将数据再次写入该存储流。 Then you try to read from the memory stream without resetting the position to the beginning of the stream.
然后,您尝试从内存流中读取而不将位置重置为流的开头。
Just create the memory stream and read from it: 只需创建内存流并从中读取:
public Image StringToImage(String str) {
byte[] imgBytes = Convert.FromBase64String(str);
return Image.FromStream(new MemoryStream(imgBytes), true);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.