将base64流解码为图像

15
我正在使用JavaScript发送客户端的base64编码图像(我正在使用http://supa.sourceforge.net/创建ASP.NET应用程序的截图上传器小程序),这会发送一个ajax请求到服务器以存储图像。在服务器上,我在ASP.NET应用程序的GenericHanlder中使用HttpContext。如何将HttpContext中的图像数据转换为图像?
2个回答

52

首先,您需要将base64转换回字节:

byte[] data = System.Convert.FromBase64String(fromBase64);

然后,您可以将其加载到 Image 的实例中:

MemoryStream ms = new MemoryStream(data);
Image img = Image.FromStream(ms);
如果你想要把它保存到文件中,可以使用System.IO.File.WriteAllBytes

请查看InputStream属性的MSDN条目。它解释了如何将数据提取为字符串:http://msdn.microsoft.com/en-us/library/system.web.httprequest.inputstream.aspx 一旦您将数据转换为字符串,按照上面所示的方法将其传递给FromBase64String方法。 - Steven Hunt

14

我需要做类似的事情,但想直接使用InputStream来处理,所以使用了以下代码进行解码:

// using System.Security.Cryptography
var stream = new CryptoStream(Request.InputStream, new FromBase64Transform(), CryptoStreamMode.Read);
var img = Image.FromStream(stream);

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接