c# - 在使用 C# 解码 Base64 字符串之前是否删除数据 :image/jpeg;base64, ?

标签 c# asp.net image base64 file-conversion

我正在尝试转换从 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/

相关文章:

c# - 发布到 Azure 的 Asp.Net 应用程序仅显示 "Your App Service app has been created"

c# - 以逗号分隔数以千计 asp.net

css - 基本 CSS 样式表

c# - 如何在 Rx.Net 中实现排放映射处理程序?

c# - 将 lambda 表达式附加到 C# 程序的 main 方法会产生什么结果?

javascript - 从动态 asp :DropDownList 中获取值

vba - 将图像添加到工作表达到了任意限制

javascript - 在 HTML5 Canvas 上旋转图像

c# - WPF 主题窗口控件以匹配 Telerik 的

c# - 在 SharePoint 2007 中使用 Silverlight 4