图像未显示在 Wpf Image Control 中

Image does not show up in Wpf Image Control

我正在重写我的应用程序,我在其中使用 Brad Barnhill (http://www.codeproject.com/Articles/20823/Barcode-Image-Generation-Library) 的 Barcode Image Generation Libary 创建条形码图像。

在这篇文章中,一切都在 Windows 表格中解释了如何做。但是现在 - 使用 Wpf - 有一些错误。例如:函数的结果 Encode returns a System.Drawing.Image 但是当我想在 Wpf Image Control 中显示此图像时 Source 属性 想要System.Windows.Media.ImageSource.

所以我研究了如何将 Drawing.Image 转换为 Media.ImageSource。我找到了一些片段,但它们没有按预期工作。

目前我使用这个代码:

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

当 运行 此代码转换图像(并将其分配给图像控件)时,没有显示任何内容

这种转换方法应该有效:

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

如果System.Drawing.Image实际上是System.Drawing.Bitmap,您还可以使用其他一些转换方法,如下所示: