Reputation: 1088
I'm re-writing a app of mine, where I create a barcode image using the Barcode Image Generation Libary
by Brad Barnhill (http://www.codeproject.com/Articles/20823/Barcode-Image-Generation-Library).
In this article everything is explaned how to do it in Windows Forms. But now - using Wpf - there are some errors. E.g.: The result of the function Encode
returns a System.Drawing.Image
but when I want to display this Image in a Wpf Image Control
the Source
property wants a System.Windows.Media.ImageSource
.
So I did some reserach of how to convert a Drawing.Image
in a Media.ImageSource
. I found some snippets but they don't work as expected.
Currently I use this code:
// Import:
using Media = System.Windows.Media;
using Forms = System.Windows.Forms;
// Setting some porperties of the barcode-object
this.barcode.RotateFlipType = this.bcvm.Rotation.Rotation;
this.barcode.Alignment = this.bcvm.Ausrichtung.Alignment;
this.barcode.LabelPosition = this.bcvm.Position.Position;
// this.bcvm is my BarcodeViewModel for MVVM
var img = this.barcode.Encode(
this.bcvm.Encoding.Encoding,
this.bcvm.EingabeWert,
this.bcvm.ForeColor.ToDrawingColor(),
this.bcvm.BackColor.ToDrawingColor(),
(int)this.bcvm.Breite,
(int)this.bcvm.Hoehe
);
this.imgBarcode.Source = img.DrawingImageToWpfImage();
this.imgBarcode.Width = img.Width;
this.imgBarcode.Height = img.Height;
// My conversion methode. It takes a Drawing.Image and returns a Media.ImageSource
public static Media.ImageSource ToImageSource(this Drawing.Image drawingImage)
{
Media.ImageSource imgSrc = new Media.Imaging.BitmapImage();
using (MemoryStream ms = new MemoryStream())
{
drawingImage.Save(ms, Drawing.Imaging.ImageFormat.Png);
(imgSrc as Media.Imaging.BitmapImage).BeginInit();
(imgSrc as Media.Imaging.BitmapImage).StreamSource = new MemoryStream(ms.ToArray());
(imgSrc as Media.Imaging.BitmapImage).EndInit();
}
return imgSrc;
}
When running this code an converting the image (and assigning it to the Image control) there is nothing displayed
Upvotes: 0
Views: 1569
Reputation: 128061
This conversion method should work:
public static ImageSource ToImageSource(this System.Drawing.Image image)
{
var bitmap = new BitmapImage();
using (var stream = new MemoryStream())
{
image.Save(stream, System.Drawing.Imaging.ImageFormat.Png);
stream.Position = 0;
bitmap.BeginInit();
bitmap.CacheOption = BitmapCacheOption.OnLoad;
bitmap.StreamSource = stream;
bitmap.EndInit();
}
return bitmap;
}
In case the System.Drawing.Image
is actually a System.Drawing.Bitmap
you may also use some other conversion methods, as shown here: fast converting Bitmap to BitmapSource wpf
Upvotes: 1