wpf 将 System.Drawing.Image 转换为 System.Windows.Media.ImageSource 没有结果

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/41998142/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-13 14:00:09  来源:igfitidea点击:

Converting System.Drawing.Image to System.Windows.Media.ImageSource with no result

c#wpfimagetype-conversionimagesource

提问by Julian Kowalczuk

I would like to convert Image to ImageSource in my WPF app. I use Code128 library which works properly (already checked in WinForms app). Function below returns ImageSource with properly size, but nothing is visible.

我想在我的 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;
        }
    }

UPDATE: The best method is one commented by Clemens below. About 4 times faster than using memorystream.

更新:最好的方法是下面克莱门斯评论的方法。大约比使用内存流快 4 倍。

回答by Clemens

You have to set BitmapCacheOption.OnLoadto make sure that the BitmapImage is loaded immediately when EndInit()is called. Without that flag, the stream would have to be kept open until the BitmapImage is actually shown.

您必须设置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;
}