C# 在运行时将字节 [] 加载到图像中
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/582805/
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
Load a byte[] into an Image at Runtime
提问by user70192
I have a byte[]that is represented by an Image. I am downloading this Imagevia a WebClient. When the WebClienthas downloaded the picture and I reference it using its URL, I get a byte[]. My question is, how do I load a byte[]into an Imageelement in WPF? Thank you.
我有一个byte[]由Image. 我正在Image通过WebClient. 当WebClient下载了图片并且我使用它的 URL 引用它时,我得到一个byte[]. 我的问题是,如何将 a 加载byte[]到ImageWPF 中的元素中?谢谢你。
Note: This is complementary to the question I asked here: Generate Image at Runtime. I cannot seem to get that approach to work, so I am trying a different approach.
注意:这是对我在这里提出的问题的补充:在运行时生成图像。我似乎无法让这种方法发挥作用,所以我正在尝试不同的方法。
采纳答案by configurator
You can use a BitmapImage, and sets its StreamSourceto a stream containing the binary data. If you want to make a streamfrom a byte[], use a MemoryStream:
您可以使用BitmapImage, 并将其StreamSource设置为包含二进制数据的流。如果stream要从 a制作a byte[],请使用 a MemoryStream:
MemoryStream stream = new MemoryStream(bytes);
回答by Jobi Joy
Create a BitmapImagefrom the MemoryStreamas below:
BitmapImage从MemoryStream下面创建一个:
MemoryStream byteStream = new MemoryStream(bytes);
BitmapImage image = new BitmapImage();
image.BeginInit();
image.StreamSource = byteStream;
image.EndInit();
And in XAML you can create an Imagecontrol and set the above imageas the Sourceproperty.
在 XAML 中,您可以创建一个Image控件并将上述内容设置image为Source属性。
回答by Thomas Amar
In .Net framework 4.0
在 .Net 框架 4.0 中
using System.Drawing;
using System.Web;
private Image GetImageFile(HttpPostedFileBase postedFile)
{
if (postedFile == null) return null;
return Image.FromStream(postedFile.InputStream);
}
回答by Kevin B Burns
One way that I figured out how to do it so that it was both fast and thread safe was the following:
我想出如何做到既快速又线程安全的一种方法如下:
var imgBytes = value as byte[];
if (imgBytes == null)
return null;
using (var stream = new MemoryStream(imgBytes))
return BitmapFrame.Create(stream,BitmapCreateOptions.None, BitmapCacheOption.OnLoad);
I threw that into a converter for my WPF application after running the images as Varbinary from the DB.
在将图像作为 Varbinary 从数据库运行后,我将其放入 WPF 应用程序的转换器中。

