Search code examples
c#wpfresx

Loading images from a relative path


I'm making a Blackjack game for a project in college (semester-long) and I've hit a road block that I can't seem to get over.

I'm trying to load the card images so they can be displayed onscreen, but I've been having very little luck in doing so. I've got absolute references down; I can load from those, but any attempt to load from a relative path fails. The project must be standalone; I can't instruct my professor to copy these images onto the root.

#if FROMDISK
        Uri myUri = new Uri(@"C:\cards\" + getFilename(r, s, "png"), UriKind.Absolute);
        PngBitmapDecoder decoder2 = new PngBitmapDecoder(myUri, BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.Default);
        BitmapSource bmp = decoder2.Frames[0];
#else
        System.Reflection.Assembly myAssembly = System.Reflection.Assembly.GetExecutingAssembly();
        Stream myStream = myAssembly.GetManifestResourceStream("Blackjack." + getFilename(r, s, "png"));
        BitmapImage bmp = new BitmapImage();
        bmp.StreamSource = myStream;
#endif
        // Draw the Image
        im.Source = bmp;
        im.Stretch = Stretch.Uniform;
        im.Width = CARD_WIDTH;

(Context)


Solution

  • You can use:

    Uri uri = new Uri(@"FolderName\FileName.png",UriKind.Relative);
    PngBitmapDecoder decoder2 = new PngBitmapDecoder(uri, BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.Default);
    

    Remember to set the properties for the image file to (otherwise the compiler will skip them) you can look the bin/debug folder after build and verify that the file is where it should be:

    • Build action: content
    • Copy to output directory: Copy always

    Another option is to make the file an embedded resource then you can access it like this:

    Bitmap bitmap = Properties.Resources.FileName;