我目前正在开发Card DLL,其中需要每个卡的图像文件作为嵌入式资源,当前项目如下所示:
注意:卡片图像(.png)位于“资源”文件夹中。
我一直在尝试的代码几乎是我唯一能找到的代码,它是:
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.");
}
}
我似乎得到的唯一异常是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);
使用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 Image控件中实际显示图像时,将抛出NullRefException。
Kaartspel kaarten = new Kaartspel();
Kaart k = kaarten.kaarten[7];
ImageSourceConverter c = new ImageSourceConverter();
testBox.Source = (ImageSource)c.ConvertFrom(k.Img); //Exception here
哪个Image
类提供了接受流的构造函数?
猜猜您可以使用System.Drawing.Image.FromStream
并将其投射到System.Drawing.Bitmap
。然后,您可以使用以下命令:
System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap(bitmap.GetHbitmap(), IntPtr.Zero, Int32Rect.Empty, BitmapSizeOptions.FromEmptyOptions());
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句