Search code examples
c#imagewinformsresourcesvisual-studio-2022

How do I add a resource as a bitmap to my C# project in Visual Studio 2022?


I know this is probably a dumb question but I've been literally trying to achieve this for like 4 hours. I looked up and down everywhere, asked ChatGPT but I was not able to find a solution.

My project is a Windows Forms project.

I can only add the resource as either an Icon or Byte[]:

enter image description here

The icon apparently has to be square, which I don't want and attempting to convert the Byte[] to Image via:

private static Image ImageFromByte(byte[] b)
{
    using MemoryStream ms = new MemoryStream(b);
    return Image.FromStream(ms);
}

This however throws an "out of memory" error.

I have no idea what I am doing wrong.


Solution

  • Update

    The latest Visual Studio can choose Bitmap as the image type now:

    Latest Editor


    I think this is a problem with the new resource editor, you can use the legacy editor to add images as Bitmap objects.

    1. Right click on the .resx file and click "Open With..."

      Step1

    2. Choose "Managed Resources Editor (Legacy)", you can also click "Set as Default" to make it the default editor.

      Step2


    Another approach is to click F7 on the .resx file to edit the XML content and manually change the image type you inserted to System.Drawing.Bitmap

    <data name="MyImage" type="System.Resources.ResXFileRef, System.Windows.Forms">
        <!--value>Resources\MyImage.jpg;System.Byte[], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value-->
        <value>Resources\MyImage.jpg;System.Drawing.Bitmap, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a</value>