【问题标题】:Get Imagesource from Memorystream in c# wpf在 c# wpf 中从 Memorystream 获取图像源
【发布时间】:2011-07-05 21:16:51
【问题描述】:

如何使用 c# 在 WPF 中从 MemoryStream 获取 ImageSource ?或将MemoryStream 转换为ImageSource 以在wpf 中将其显示为图像?

【问题讨论】:

    标签: c# wpf memorystream imagesource


    【解决方案1】:
    using (MemoryStream memoryStream = ...)
    {
        var imageSource = new BitmapImage();
        imageSource.BeginInit();
        imageSource.StreamSource = memoryStream;
        imageSource.EndInit();
    
        // Assign the Source property of your image
        image.Source = imageSource;
    }
    

    【讨论】:

      【解决方案2】:
      如果您在分配给Image.Source 之前处理了流,则除了@Darin Dimitrov 答案之外,什么都不会显示,所以要小心

      例如,Next 方法将不起作用,From one of my projects using LiteDB

      public async Task<BitmapImage> DownloadImage(string id)
      {
          using (var stream = new MemoryStream())
          {
              var f = _appDbManager.DataStorage.FindById(id);
              f.CopyTo(stream);
              var imageSource = new BitmapImage {CacheOption = BitmapCacheOption.OnLoad};
              imageSource.BeginInit();
              imageSource.StreamSource = stream;
              imageSource.EndInit();
              return imageSource;
          }
      }
      
      

      你不能使用最后一个函数返回的imageSource

      但是这个实现会起作用

      
      public async Task<BitmapImage> DownloadImage(string id)
      {
          // TODO: [Note] Bug due to memory leaks, if we used Using( var stream = new MemoryStream()), we will lost the stream, and nothing will shown
          var stream = new MemoryStream();
          var f = _appDbManager.DataStorage.FindById(id);
          f.CopyTo(stream);
          var imageSource = new BitmapImage {CacheOption = BitmapCacheOption.OnLoad};
          imageSource.BeginInit();
          imageSource.StreamSource = stream;
          imageSource.EndInit();
          return imageSource;
      }
      

      【讨论】:

        猜你喜欢
        • 2011-12-13
        • 1970-01-01
        • 2016-06-17
        • 2019-06-05
        • 2011-05-16
        • 2012-06-04
        • 2016-11-13
        • 1970-01-01
        相关资源
        最近更新 更多