Load picturebox image in C# from file in relative path

余生长醉 提交于 2019-12-10 14:32:55

问题


I have a picturebox image in a Windows Form Solution. After user selects an item from a database, I want to load an image into this picturebox. The filename of the image will come from the database and all images must be stored in a subfolder of the application folder (\Images). I don't want to include all these (2000-3000 images) in my solution, besides, more images will be added by users as the database grows. Also, I don't want to code an absolute path. So this is not what I want:

pictureBox.Image = Image.FromFile(@"C:\Program Files\Application\Images\" + dbase.filename);

I want to code a relative path to the image folder, so regardless of where the application will be installed, the images can be loaded from this particular subfolder. I've tried things like these, using a temporary test-image called "test.jpg":

pictureBox.Image = Image.FromFile(@"Images\test.jpg");
pictureBox.Image = Image.FromFile(@"..\Images\test.jpg");
pictureBox.Image = Image.FromFile(@"|DataDirectory|\Images\test.jpg");

But these don't work. I can only get it to work with an absolute path, like "C:\Images\test.jpg". What should I do?


回答1:


Have you tried the PictureBox.Load Method?

If the url parameter indicates a local file, the recommended format is a local file path. For example, an image file named myPicture.jpglocated atc:\ would be accessed by passing c:\myPicture.jpg for the url parameter. A full path, such as http://www.contoso.com/path/images/image.jpg, or a relative path, such as ./images/image.jpg, can be used. If a relative path is used, it will be considered relative to the working directory. A call to the Load method sets the ImageLocation property to the value of url.




回答2:


I would use reflection to get the executing directory, such as:

string ImagesDirectory = 
    Path.Combine(
        Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location),
        "Images"
    );



回答3:


The best way to load an image to a picturbox is, load required image from your project resource folder.

For this do the following:

  1. add required images to resource folder.
  2. load image to picturebox from resource folder.

    Form1.pictureBox1.Image = yourProject.Properties.Resources.YourImage;

Note: image type is not required [.bmp, .jpg etc]



来源:https://stackoverflow.com/questions/24764353/load-picturebox-image-in-c-sharp-from-file-in-relative-path

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