使用GetManifestResourceStream找不到嵌入式资源

Yor*_*ick 7 c# system.drawing stream embedded-resource

我目前正在开发一个卡DLL,我需要将每张卡的图像文件作为嵌入式资源,当前项目如下所示:

卡片图像位于Resources文件夹中

注意:卡片图像(.png)位于Resources文件夹中.

我一直在尝试的代码,几乎是我能找到的唯一代码,是这样的:

Assembly _assembly;
Stream _imageStream;

private Image img;
public Image Img
{ 
get
    {
        return img;
    }
}

public Kaart() : this(5, "Spades") { }

public Kaart(int val, string s)
{
    this.KaartWaarde = val;
    this.Figuur = s;
    this._imageStream = imgS();
    this.img = new Image(_imageStream);
}

private Stream imgS()
{
    try
    {
        _assembly = Assembly.GetExecutingAssembly();
        Stream s = _assembly.GetManifestResourceStream(string.Format("{0}{1}.png", this.kaartWaarde, this.figuur.Substring(0, 1)));
        if (s != null)
            return s;
        else
            return null ;
    }
    catch
    {
        throw new Exception("Kaart kan niet geladen worden.");
    }
}
Run Code Online (Sandbox Code Playgroud)

我似乎唯一的例外是在创建Kaart代码所在的对象时出现异常:

Kaart k = null;
try
{
    k = new Kaart();
}
catch (Exception ex)
{
    MessageBox.Show(ex.Message); //This MessageBox is being shown
}
ImageSourceConverter c = new ImageSourceConverter();
testBox.Source = (ImageSource)c.ConvertFrom(k.Img);
Run Code Online (Sandbox Code Playgroud)

使用MessageBox捕获和显示的异常如下:

'null'的值对'stream'无效.

在代码执行期间观察我的变量时,我注意到了某种方式

Stream s = _assembly.GetManifestResourceStream(string.Format("{0}{1}.png", this.kaartWaarde, this.figuur.Substring(0, 1)));

即使使用格式,也无法找到图像 Kaarten.{0}{1}.png

这简直让我想知道我在这里做错了什么,或者我是否使用了错误的语法.有任何想法吗?

编辑:图像正在正确加载,但ImageSourceConverter仍在抛出 NullReferenceException

卡片创建和加载Stream对象(并将它们卸载到Image对象中)现在工作正常,但是当我尝试使用下面的代码在我的WPF图像控件中实际显示图像时,会抛出NullRefException.

Kaartspel kaarten = new Kaartspel();

Kaart k = kaarten.kaarten[7];

ImageSourceConverter c = new ImageSourceConverter();
testBox.Source = (ImageSource)c.ConvertFrom(k.Img); //Exception here
Run Code Online (Sandbox Code Playgroud)

Rob*_* S. 1

哪个Image类提供了接受流的构造函数?

我猜你可以使用System.Drawing.Image.FromStream并将其投射到System.Drawing.Bitmap. 然后您可以使用以下内容:

System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap(bitmap.GetHbitmap(), IntPtr.Zero, Int32Rect.Empty, BitmapSizeOptions.FromEmptyOptions());