图像未显示在Wpf图像控件中

时间:2016-10-10 14:00:05

标签: c# wpf image system.drawing

我正在重写我的应用程序,在那里我使用Brad Barnhill(Working table just with text)的Barcode Image Generation Libary创建条形码图像。

在本文中,所有内容都解释了如何在Windows窗体中执行此操作。但现在 - 使用Wpf - 有一些错误。例如:函数Encode的结果返回System.Drawing.Image,但当我想在Wpf Image Control中显示此图片时,Source属性需要System.Windows.Media.ImageSource。< / p>

所以我做了一些关于如何在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;
}

运行此代码时,转换图像(并将其指定给图像控件)没有任何显示

1 个答案:

答案 0 :(得分:1)

此转换方法应该有效:

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,您还可以使用其他一些转换方法,如下所示:fast converting Bitmap to BitmapSource wpf