在运行时将一个byte 加载到Image中

我有一个由Image表示的byte[] 。 我正在通过WebClient下载此Image 。 当WebClient下载了图片并使用其URL引用它时,我得到一个byte[] 。 我的问题是,如何将一个byte[]加载到WPF中的Image元素中? 谢谢。

注意 :这是我在此处提出的问题的补充: 在运行时生成图像 。 我似乎无法使用这种方法,所以我尝试了一种不同的方法。

您可以使用BitmapImage ,并将其StreamSource设置为包含二进制数据的流。 如果要从byte[]创建stream ,请使用MemoryStream

 MemoryStream stream = new MemoryStream(bytes); 

MemoryStream创建一个BitmapImage ,如下所示:

 MemoryStream byteStream = new MemoryStream(bytes); BitmapImage image = new BitmapImage(); image.BeginInit(); image.StreamSource = byteStream; image.EndInit(); 

在XAML中,您可以创建一个Image控件并将上面的image设置为Source属性。

在.Net framework 4.0中

 using System.Drawing; using System.Web; private Image GetImageFile(HttpPostedFileBase postedFile) { if (postedFile == null) return null; return Image.FromStream(postedFile.InputStream); } 

我想出了如何做到这一点以便快速和线程安全的一种方法如下:

  var imgBytes = value as byte[]; if (imgBytes == null) return null; using (var stream = new MemoryStream(imgBytes)) return BitmapFrame.Create(stream,BitmapCreateOptions.None, BitmapCacheOption.OnLoad); 

在将数据库中的图像作为Varbinary运行后,我将其转换为我的WPF应用程序的转换器。