【问题标题】:Load a byte[] into an Image at Runtime在运行时将 byte[] 加载到图像中
【发布时间】:2010-10-09 15:05:13
【问题描述】:

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

注意:这是对我在这里提出的问题的补充:Generate Image at Runtime。我似乎无法让这种方法发挥作用,所以我正在尝试一种不同的方法。

【问题讨论】:

  • 请注意,我希望将 byte[] 加载到 System.Windows.Controls.Image 实例中。不是每个人都指出的 System.Drawing.Image 实例。

标签: c# wpf image


【解决方案1】:

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

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

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

【讨论】:

    【解决方案2】:

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

    MemoryStream stream = new MemoryStream(bytes);
    

    【讨论】:

      【解决方案3】:

      在 .Net 框架 4.0 中

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

      【讨论】:

        【解决方案4】:

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

         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 应用程序的转换器中。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2012-08-06
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多