tags:

views:

7015

answers:

4

I have an image in my projects stored in Resources/myimage.jpg in the project. How can I dynamically load this image into Bitmap object?

+9  A: 

Are you using Windows Forms? If you've added the image using the Properties/Resources UI, you get access to the image from generated code, so you can simply do this:

var bmp = new Bitmap(WindowsFormsApplication1.Properties.Resources.myimage);
Matt Hamilton
No, it is added as a plain file into the folder Resources.
SeasonedCoder
Ah ok. In that case I think @Hallgrim's got the answer for you using resource streams. If you *are* using Windows Forms I would urge you to delete the image and re-add it from the UI - much easier that way.
Matt Hamilton
+6  A: 

You can get a reference to the image the following way:

Image myImage = Resources.myImage;

If you want to make a copy of the image, you'll need to do the following:

Bitmap bmp = new Bitmap(Resources.myImage);

Don't forget to dispose of bmp when you're done with it. If you don't know the name of the resource image at compile-time, you can use a resource manager:

ResourceManager rm = Resources.ResourceManager;
Bitmap myImage = (Bitmap)rm.GetObject("myImage");

The benefit of the ResourceManager is that you can use it where Resources.myImage would normally be out of scope, or where you want to dynamically access resources. Additionally, this works for sounds, config files, etc.

Charlie Salts
Note: use Properties.Resources.myImage;
splattne
+7  A: 

You need to load it from resource stream.

Bitmap bmp = new Bitmap(
  System.Reflection.Assembly.GetEntryAssembly().
    GetManifestResourceStream("MyProject.Resources.myimage.png"));

If you want to know all resource names in your assembly, go with:

string[] all = System.Reflection.Assembly.GetEntryAssembly().
  GetManifestResourceNames();

foreach (string one in all) {
    MessageBox.Show(one);
}
Josip Medved
You should not need to use reflection - this seems overly complicated given the simpler methods available.
Charlie Salts
This one worked for me. Thanks !
SeasonedCoder
+7  A: 

The best thing is to add them as Image Resources in the Resources settings in the Project. Then you can get the image directly by doing Resources.myimage. This will get the image via a generated C# property.

If you just set the image as Embedded Resource you can get it with:

string name = "Resources.myimage.jpg"
string namespace = "MyCompany.MyNamespace";
string resource = namespace + "." + name;
Bitmap image = new Bitmap(type.Assembly.GetManifestResourceStream(resource));
Hallgrim