Search code examples
c#resx

Store Image in .resx as byte[] rather than Bitmap


Slightly daft, but...

Is there a way to prevent Visual Studio treating a .jpg file in a .resx as a Bitmap so that I can access a byte[] property for the resource instead?

I just want:

byte[] myImage = My.Resources.MyImage;

Solution

  • Try using an "Embedded Resource" instead

    So lets say you have a jpg "Foo.jpg" in ClassLibrary1. Set the "Build Action" to "Embedded Resource".

    Then use this code to get the bytes

    byte[] GetBytes()
    {
        var assembly = GetType().Assembly;
        using (var stream = assembly.GetManifestResourceStream("ClassLibrary1.Foo.jpg"))
        {
            var buffer = new byte[stream.Length];
            stream.Read(buffer, 0, (int) stream.Length);
            return buffer;
        }
    }
    

    Or, alternatively, if you want a more re-usable method

    byte[] GetBytes(string resourceName)
    {
        var assembly = GetType().Assembly;
        var fullResourceName = string.Concat(assembly.GetName().Name, ".", resourceName);
        using (var stream = assembly.GetManifestResourceStream(fullResourceName))
        {
            var buffer = new byte[stream.Length];
            stream.Read(buffer, 0, (int) stream.Length);
            return buffer;
        }
    }
    

    and call

     var bytes = GetBytes("Foo.jpg");