Julian Kowalczuk Julian Kowalczuk - 4 years ago 171
C# Question

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


If you have better solution to convert it go ahead. Thanks for reply!

Answer Source

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;
}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download