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

可紊 提交于 2019-12-10 14:01:54

问题


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.

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.


回答1:


You have to set BitmapCacheOption.OnLoad to 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.

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;
}


来源:https://stackoverflow.com/questions/41998142/converting-system-drawing-image-to-system-windows-media-imagesource-with-no-resu

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!