c# - 将 System.Drawing.Image 转换为 System.Windows.Media.ImageSource 没有结果

标签 c# wpf image type-conversion imagesource

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

更新: 最好的方法是 this .比使用 MemoryStream 快大约 4 倍。

最佳答案

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

关于c# - 将 System.Drawing.Image 转换为 System.Windows.Media.ImageSource 没有结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41998142/

相关文章:

位图中的 C# 内存泄漏

asp.net - 如何在asp.net的Gridview中获取路径存储在数据库中的图像

c# - 在 Asp.net 中使用 HTML5 的拖放上传文件

c# - 如何用伪代码写前置条件

c# - 使用 SQL WHERE IN 从 CheckboxList 中检索多个值

c# - 确定 WPF 元素类型

c# - 触摸 WPF 中的 Bug?

c# - FluentValidation 规则链接不会在第一次失败时停止

asp.net - 拿到身份证了吗?当前用户是否喜欢SharePoint?

html - 如何在我的网站的团队部分居中图像