Julian Kowalczuk
Julian Kowalczuk

Reputation: 145

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

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 this. About 4 times faster than using MemoryStream.

Upvotes: 7

Views: 24572

Answers (1)

Clemens
Clemens

Reputation: 128013

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

Upvotes: 19

Related Questions