如何从C#项目的Resources文件夹中检索Image

我在项目的资源文件夹中有一些图像,但我想从项目的这些资源文件中更改图片框

考虑使用Properties.Resources.yourImage

Properties.Resources包含您作为资源添加的所有内容(请参阅项目属性,资源选项卡)

除此之外,如果您将图像作为资源嵌入到项目中,您可以通过在已嵌入图像的程序集上调用GetManifestResourceStream来获取它们,类似于

 Stream imgStream = Assembly.GetExecutingAssembly().GetManifestResourceStream( "YourNamespace.resources.ImageName.bmp"); pictureBox.Image = new Bitmap(imgStream); 

不要忘记将图像标记为嵌入式资源! (您需要在其属性窗口中为图像设置构建操作)

如果您发现从GetManifestResourceStream继续返回null ,您可能会给出错误的名称。 (可能很难得到正确的名称)在程序集上调用GetManifestResourceNames ; 这将返回所有资源名称,您可以在列表中找到所需的名称。

 string img = null; private void btnShow_Click(object sender, EventArgs e) { string imgName; img = textBox1.Text; imgName = "images/" + img + ".jpg"; if (imgName == null) { MessageBox.Show("no photo"); } else if (imgName != null) { this.picBox1.Image = Image.FromFile("images/" + img + ".jpg"); } } 

下面是从资源文件夹中获取图像的代码。 通常我们将图像保存在资源文件夹中。 但有时我们只有我们的图像名称。 在这种情况下,您只能使用图像名称从资源文件夹访问图像。

下面的代码将展示它。

 private System.Resources.ResourceManager RM = new System.Resources.ResourceManager("YourAppliacationNameSpace.Properties.Resources", typeof(Resources).Assembly); PbResultImage.Image = (Image)RM.GetObject(YourPictureName); 
  • YourAppliacationNameSpace表示您的应用程序的名称。
  • YourPictureName表示您要从资源文件夹访问的图片。 但图片名称必须没有扩展名,例如(PNG,GIF,JPEG等)

希望我对某个人有益。

谢谢。

萨拉姆。

为我工作:

 (Bitmap) Properties.Resources.ResourceManager.GetObject("ImageName");