Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 one commented by Clemens below. About 4 times faster than using memorystream.

like image 627
Julian Kowalczuk Avatar asked Feb 02 '17 09:02

Julian Kowalczuk


1 Answers

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;
}
like image 108
Clemens Avatar answered Oct 01 '22 01:10

Clemens