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

Julian Kowalczuk picture Julian Kowalczuk · Feb 2, 2017 · Viewed 16k times · Source

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.

Answer

Clemens picture Clemens · Feb 2, 2017

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