C# 将 base64 流解码为图像

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12901705/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 00:53:45  来源:igfitidea点击:

Decoding base64 Stream to image

c#javascriptasp.net

提问by sunil5715

I am sending base64 encoded image from client side using javascript (I am creating Screenshot uploader applet for asp.net application using http://supa.sourceforge.net/) and this sends an ajax request to server to store the image. At server I am using HttpContext in GenericHanlder in asp.net application.

我正在使用 javascript 从客户端发送 base64 编码的图像(我正在使用http://supa.sourceforge.net/为 asp.net 应用程序创建屏幕截图上传程序小程序),这会向服务器发送一个 ajax 请求以存储图像。在服务器上,我在 asp.net 应用程序的 GenericHanlder 中使用 HttpContext。

How to convert image data from HttpContext to image at server?

如何将图像数据从 HttpContext 转换为服务器上的图像?

采纳答案by Steven Hunt

First, you need to convert the base 64 back into bytes:

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

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

Then, you can load it into an instance of Image:

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

MemoryStream ms = new MemoryStream(data);
Image img = Image.FromStream(ms);

If you want to save it to a file instead, use System.IO.File.WriteAllBytes

如果要将其保存到文件,请使用System.IO.File.WriteAllBytes

回答by DigitalDan

I needed to do something similar, but wanted to work directly with the InputStream, so used this to do the decoding:

我需要做类似的事情,但想直接使用 InputStream,所以用它来做解码:

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