Accessing an image resource by name and assigning it to a PictureBox

本小妞迷上赌 提交于 2019-12-08 06:33:45

问题


I have this list:

List<string> list = new List<string>();
list.Add("dog.jpg");
list.Add("cat.jpg");
list.Add("horse.jpg");

In my resources, I have 3 images named: dog, cat, and horse. I want to display them in a picture box using the list.

I have tried something like this:

pictureBox1.Image = project.Properties.Resources.list[2]; // should display the horse image

The problem is that it displays the error:

'Resources' does not contain a definition for 'list' `

How can I get the image using the name in the list?


回答1:


Properties.Resources only knows the resources (dog, cat, and horse) so you can't give him a string and expect him to know the resource. You need to use the GetObject method from the ResourceManager like this:

(Bitmap)Properties.Resources.ResourceManager.GetObject(list[2])

This should give you the horse image.




回答2:


When you add images, strings, etc. to a resource file (.resx), Visual Studio automatically generates strongly-typed properties in the corresponding Resources class for you. So for example, if you added horse.jpg to Resources.resx in your project, there should be a horse property on the Properties.Resources class which returns a System.Drawing.Bitmap. So you should be able to do:

pictureBox1.Image = Properties.Resources.horse;

If you want to be able to access an image resource by name, then you can do it the same way the generated code does it, using ResourceManager.GetObject. But note the image resource name will not include the .jpg extension and you will have to cast the result to a Bitmap:

pictureBox1.Image = (Bitmap)Properties.Resources.ResourceManager.GetObject("horse");

You could create a helper method which will strip the extension off the filename and retrieve the resource, like this:

private Bitmap GetImageResource(string filename)
{
    string resourceName = filename.Substring(0, filename.IndexOf("."));
    return (Bitmap)Properties.Resources.ResourceManager.GetObject(resourceName);
}

That would allow you to use it with your list like this:

pictureBox1.Image = GetImageResource(list[2]);



回答3:


Try calling pictureBox1.Refresh(); after assigning the image.



来源:https://stackoverflow.com/questions/47592576/accessing-an-image-resource-by-name-and-assigning-it-to-a-picturebox

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!