Search code examples
c#streamembedded-resourcesystem.drawing

Can't find embedded resource using GetManifestResourceStream


I'm currently working on a Card DLL in which I would need the image files for each card as an embedded resource, the current project looks like this:

Card images are in the Resources folder

Note: The card images (.png) are in the Resources folder.

The code I've been trying & is pretty much the only code I can find, is this:

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.");
    }
}

The only exception I seem to get is an exception in the creation of the Kaart object for which the code is here:

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

The exception being caught & shown by use of MessageBox is as follows:

Value of 'null' is not valid for 'stream'.

While watching my variables during code execution, I noticed somehow the line

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

Fails to find the image, even when using the format Kaarten.{0}{1}.png

This simply makes me wonder if I'm doing something wrong here or if I'm using the wrong syntax. Any ideas?

EDIT: Images are now being loaded properly, however the ImageSourceConverter is still throwing a NullReferenceException

Card creation & loading the Stream objects (and unloading them into an Image object) are working fine now as far as I can tell, however when trying to actually show the images in my WPF Image control using the code below, the NullRefException is thrown.

Kaartspel kaarten = new Kaartspel();

Kaart k = kaarten.kaarten[7];

ImageSourceConverter c = new ImageSourceConverter();
testBox.Source = (ImageSource)c.ConvertFrom(k.Img); //Exception here

Solution

  • Which Image class provides a constructor that accepts a stream?

    Guess you could use System.Drawing.Image.FromStream and cast it to System.Drawing.Bitmap. Then you can use the following:

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