我正在尝试转换从 Canvas 元素调整大小的图像生成的 Base64 编码字符串,但在使用 Convert.FromBase64() 进行转换时出现以下错误
The input is not a valid Base-64 string as it contains a non-base 64 character, more than two padding characters, or an illegal character among the padding characters.
编码数据看起来像这样以=开始和结束
data:image/jpeg;base64,/...=
我不太明白的是,当我执行 Convert.FromBase64() 时,我是否需要去掉 data:image/jpeg;base64, 的前缀,然后解码其余部分?
我用来解码的代码如下
string base64String = newinput.Value.ToString();
// Convert Base64 String to byte[]
byte[] imageBytes = Convert.FromBase64String(base64String);
MemoryStream ms = new MemoryStream(imageBytes, 0, imageBytes.Length);
// Convert byte[] to Image
ms.Write(imageBytes, 0, imageBytes.Length);
System.Drawing.Image image = System.Drawing.Image.FromStream(ms, true);
string newFile = Guid.NewGuid().ToString() + ".jpg";
image.Save(Path.Combine(Server.MapPath("~/Assets/") + Request.QueryString["id"] + "/", newFile), ImageFormat.Jpeg);
基本上,我将字符串转换为图像并保存在服务器上。正如你所看到的,我正在使用 C#
有什么想法吗?
最佳答案
do I need to strip off the prefix of data:image/jpeg;base64, and then decode the remainder?
是的 - 前缀不是 Base64 编码的文本,它只是表示其余部分是 Base64 编码的(以及 mime 类型是什么)。
我们并不确切知道您如何获取数据,但请注意,您应该首先检查数据 URL 是否声明为 Base64 编码。
关于c# - 在使用 C# 解码 Base64 字符串之前是否删除数据 :image/jpeg;base64, ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30573980/