Home > Net >  Accessing Images from resources.resx file not working with Image.FromFile method
Accessing Images from resources.resx file not working with Image.FromFile method

Time:12-25

I have an Image array, and I want to set an image in that array to be an image from Resources.resx file, I wrote this code here and gave me the exception that the image wasn't found.

string path = "PeanutToTheDungeon.Properties.Resources.ScaredMeter1"
imageArray[0] = Image.FromFile(path);

Does anyone know how to access local files using a path? Also, the file does exist and it is named correctly too.

CodePudding user response:

EmbeddedResources are not files, they are binary data encoded into the assembly itself. There are multiple ways to read them, the most common being to use the generated code from the resx (e.g., Resources.MyImageName).

The easiest way is just to do that. Find the .resx file in Visual Studio and look for the Resources.Designer.cs file. Inside that, you will find the generated property "ScaredMeter1", and it will likely be of type Bitmap (which derives from Image). To use it, you would have this code:

imageArray[0] = PeanutToTheDungeon.Properties.Resources.ScaredMeter1;

You can also create the image yourself like this:

using System;
using System.Collections.Generic;
using System.Drawing;
using System.Reflection;

internal static class EmbeddedResourceHelper
{
    /// <summary>
    /// Creates a new <see cref="System.Drawing.Image"/> by reading a <see cref="Stream"/> from an embedded resource.
    /// </summary>
    /// <param name="assembly">Assembly containing the embedded resource.</param>
    /// <param name="resourceName">Name of the resource.</param>
    /// <returns>The created <see cref="Image"/>.</returns>
    /// <exception cref="ArgumentNullException">One of the arguments was <c>null</c>.</exception>
    /// <exception cref="KeyNotFoundException">A resource named <paramref name="resourceName"/> was not found in <paramref name="assembly"/>.</exception>
    public static Image ReadEmbeddedResourceImage(Assembly assembly, string resourceName)
    {
        if (assembly is null)
        {
            throw new ArgumentNullException(nameof(assembly));
        }

        if (resourceName is null)
        {
            throw new ArgumentNullException(nameof(resourceName));
        }

        using Stream stream = assembly.GetManifestResourceStream(resourceName)
            ?? throw new KeyNotFoundException($"{resourceName} is not a valid resource in {assembly.FullName}");

        var image = Image.FromStream(stream);
        return image;
    }
}
  • Related