How to add a resource as a bitmap to C# project in Visual Studio

By FoxLearn 11/20/2024 6:43:05 AM   158
Adding a bitmap or other resource to a C# project in Visual Studio 2022 involves a few steps, including embedding the resource and accessing it in your code.

When adding an image resource in a Windows Forms project, the default resource editor sometimes stores it as a byte[] instead of a System.Drawing.Bitmap.

To add images as Bitmap objects, you can use the legacy resource editor.

Right-click your .resx file in the Solution Explorer, then click "Open With..."

visual studio open with

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

managed resources editor

In the legacy editor, add your bitmap using Add Existing File.... This ensures it is stored as a System.Drawing.Bitmap.

Open the .resx file in the legacy editor or XML editor (F7) and ensure the <data> entry for the image specifies System.Drawing.Bitmap.

For example:

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

Once added correctly as a System.Drawing.Bitmap, you can access it via Properties.Resources:

Bitmap bitmap = Properties.Resources.MyImage;