【问题标题】:BitmapSource from file来自文件的位图源
【发布时间】:2022-03-04 10:41:53
【问题描述】:

如何从图像文件加载BitmapSource

【问题讨论】:

    标签: c# wpf


    【解决方案1】:
    • The BitmapImage class is a non-asbtract subclass of BitmapSource,所以只需使用 new BitmapImage(Uri) 构造函数并将新实例传递给任何需要 BitmapSource 对象的对象。
    • 不要被参数类型是 System.Uri 的事实所迷惑:Uri 不仅适用于 http:// 地址,还适用于本地文件系统路径和 UNC 共享等。李>

    所以这对我有用:

    BitmapImage thisIsABitmapImage = new BitmapImage(new Uri("c:\\image.bmp"));
    
    BitmapSource thisIsABitmapImageUpcastToBitmapSource = thisIsABitmapImage;
    

    【讨论】:

      【解决方案2】:

      您可以将图像的字节从磁盘读取到字节数组中,然后创建您的 BitmapImage 对象。

      var stream = new MemoryStream(imageBytes);
      var img = new System.Windows.Media.Imaging.BitmapImage();
      
      img.BeginInit();
      img.StreamSource = stream;
      img.EndInit();
      
      return img;
      

      【讨论】:

      • 但这会泄漏 MemoryStream!您需要设置 CacheOption = OnLoad 并在之后处理流。
      • 据我所知,没有理由释放 MemoryStream,它只是一个字节数组的包装器,并且该类的 dispose 方法有一个空实现。
      【解决方案3】:

      代码如下:

      FileStream fileStream = 
          new FileStream(fileName, FileMode.Open, FileAccess.Read);
      
      var img = new System.Windows.Media.Imaging.BitmapImage();
      img.BeginInit();
      img.StreamSource = fileStream;
      img.EndInit();
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-08-25
        • 1970-01-01
        • 1970-01-01
        • 2020-11-30
        • 2023-04-02
        • 2011-04-27
        • 2015-08-18
        • 1970-01-01
        相关资源
        最近更新 更多