【问题标题】:Image does not show up in Wpf Image Control图像未显示在 Wpf 图像控件中
【发布时间】:2017-02-18 23:32:55
【问题描述】:

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

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

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

目前我使用这个代码:

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

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

【问题讨论】:

    标签: c# wpf image system.drawing


    【解决方案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

    【讨论】:

    • 谢谢克莱门斯!在尝试了您的代码后,我注意到我刚刚搞砸了我的 XAML。图像控件被外部堆栈面板边框混合所掩盖。但是您的代码也可以:D
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-07-22
    • 2012-07-05
    相关资源
    最近更新 更多