【问题标题】:Converting System.Drawing.Image to System.Windows.Media.ImageSource with no result将 System.Drawing.Image 转换为 System.Windows.Media.ImageSource 没有结果
【发布时间】:2017-06-19 06:48:52
【问题描述】:

我想在我的 WPF 应用程序中将 Image 转换为 ImageSource。我使用正常工作的 Code128 库(已在 WinForms 应用程序中检查)。下面的函数返回大小合适的 ImageSource,但什么都看不见。

private ImageSource generateBarcode(string number)
    {
        var image = Code128Rendering.MakeBarcodeImage(number, 1, false);
        using (var ms = new MemoryStream())
        {
            var bitmapImage = new BitmapImage();
            image.Save(ms, ImageFormat.Bmp);
            bitmapImage.BeginInit();
            ms.Seek(0, SeekOrigin.Begin);
            bitmapImage.StreamSource = ms;
            bitmapImage.EndInit();
            return bitmapImage;
        }
    }

更新: 最好的方法是 Clemens 在下面评论的一种方法。比使用 memorystream 快约 4 倍。

【问题讨论】:

    标签: c# wpf image type-conversion imagesource


    【解决方案1】:

    您必须设置BitmapCacheOption.OnLoad 以确保在调用EndInit() 时立即加载BitmapImage。如果没有该标志,则流必须保持打开状态,直到实际显示 BitmapImage。

    using (var ms = new MemoryStream())
    {
        image.Save(ms, ImageFormat.Bmp);
        ms.Seek(0, SeekOrigin.Begin);
    
        var bitmapImage = new BitmapImage();
        bitmapImage.BeginInit();
        bitmapImage.CacheOption = BitmapCacheOption.OnLoad;
        bitmapImage.StreamSource = ms;
        bitmapImage.EndInit();
    
        return bitmapImage;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2010-11-15
      • 1970-01-01
      • 2011-04-14
      • 2011-01-25
      • 1970-01-01
      • 1970-01-01
      • 2020-02-09
      • 1970-01-01
      相关资源
      最近更新 更多