Getting an image out of the resources

Hi there,

I added a jpg-image to the project resources and want to use it, but don't know how. :-/
I did not compile any new resource file, I just did a right-click on "resources" chose "add resource", then set the extensions to "*.*" to see all files and added my jpg-image.
Here is what I tried to get this image:
 

System.Resources.ResourceManager res =
                new System.Resources.ResourceManager(typeof(MainForm));

PictureBox PB2 = new PictureBox();
PB2.Image = ((System.Drawing.Image)(res.GetObject("IMG.jpg")));
PB2.Location = new System.Drawing.Point(0, 0);
PB2.Size = new System.Drawing.Size(30, 30);

PB2.Show();
this.Refresh();

Thanks for any help,
Finch82.



Answer this question

Getting an image out of the resources

  • JM-Taz

    OK,

    I found out how to do this:
    Add a new resource file to the project. Since I use SharpDevelop, I do this by right-clicking onto the "project view", click "add file", select "misc", choose "empty resource file".
    Than I set its compile action to "EmbedAsResource".
    The following code will receive an image out of my resource, assuming the resource file is labled "<namespace>.<category>.resource", where namespace is the actual namespace of my project and category just a name so I have some structure in my resource files (Images, Strings, whatever):

    System.Resources.ResourceManager rm new System.Resources.ResourceManager(
                                                                 
    "NameOfResourceFile",
                                                                 
    System.Reflection.Assembly.GetExecutingAssembly()
                                                                  );

    Image image = (Image) rm.GetObject("MyPicture");  //no extension needed

    Finch82.


  • Sinical

    ...since I was asked this several times, here an example:

    Name of physical resource file:
    Images.resources (NAMESPACE.Images.resources)

    Code to access resource file:
    System.Resources.ResourceManager rm new System.Resources.ResourceManager(
                                                                 
    "Images", ("NAMESPACE.Images")
                                                                 
    System.Reflection.Assembly.GetExecutingAssembly()
                                                                  );

    Code to receive the image named "Background.jpg" out of the resource file:
    Image image = (Image) rm.GetObject("Background");  //no extension needed


  • Getting an image out of the resources