在C#中从相对路径的文件中加载图片框图像 [英] Load picturebox image in C# from file in relative path

查看:405
本文介绍了在C#中从相对路径的文件中加载图片框图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在Windows窗体解决方案中有一个图片框图像。用户从数据库中选择一个项目后,我想将图像加载到此图片框中。图像的文件名将来自数据库,所有图像必须存储在应用程序文件夹(\Images)的子文件夹中。
我不想在我的解决方案中包含所有这些(2000-3000图像),此外,随着数据库的增长,用户将添加更多图像。
另外,我不想编写绝对路径。所以这不是我想要的:

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);

我想编写图像文件夹的相对路径,因此无论应用程序安装在何处,图像可以从这个特定的子文件夹加载。
我尝试过这样的事情,使用名为test.jpg的临时测试图像:

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");

但这些不起作用。我只能使用绝对路径,比如C:\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?

推荐答案

你试过 PictureBox.Load方法


如果url参数指示本地文件,则建议的格式是本地文件路径。例如,通过传递c:\ myPicture.jpg获取url参数,可以访问名为myPicture.jpglocated atc:\的图像文件。完整路径,例如 http://www.contoso.com/path/images/image可以使用.jpg 或相对路径,例如./images/image.jpg。如果使用相对路径,则将其视为相对于工作目录。对Load方法的调用将ImageLocation属性设置为url的值。

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.

这篇关于在C#中从相对路径的文件中加载图片框图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆