我的项目中有一张图像存储在Resources/myimage.jpg中。我如何动态加载这张图像到位图对象?


当前回答

最好的方法是将它们作为图像资源添加到项目的资源设置中。然后可以通过执行Resources.myimage直接获取映像。这将通过一个生成的c#属性获取图像。

如果你只是将图像设置为嵌入式资源,你可以通过:

string name = "Resources.myimage.jpg"
string namespaceName = "MyCompany.MyNamespace";
string resource = namespaceName + "." + name;
Type type = typeof(MyCompany.MyNamespace.MyTypeFromSameAssemblyAsResource);
Bitmap image = new Bitmap(type.Assembly.GetManifestResourceStream(resource));

其中mytypefrommsameassemblyasresource是程序集中的任何类型。

其他回答

最好的方法是将它们作为图像资源添加到项目的资源设置中。然后可以通过执行Resources.myimage直接获取映像。这将通过一个生成的c#属性获取图像。

如果你只是将图像设置为嵌入式资源,你可以通过:

string name = "Resources.myimage.jpg"
string namespaceName = "MyCompany.MyNamespace";
string resource = namespaceName + "." + name;
Type type = typeof(MyCompany.MyNamespace.MyTypeFromSameAssemblyAsResource);
Bitmap image = new Bitmap(type.Assembly.GetManifestResourceStream(resource));

其中mytypefrommsameassemblyasresource是程序集中的任何类型。

使用以下一种。我已经用Windows窗体的网格视图单元进行了测试。

Object rm = Properties.Resources.ResourceManager.GetObject("Resource_Image");
Bitmap myImage = (Bitmap)rm;
Image image = myImage;

名称为“Resource_Image”,可以从项目中找到。

在项目名称下,您可以找到Properties。扩大它。在那里您可以看到参考资料。resx文件。打开它。将文件名应用为“Resource_Image”。

在我的情况下——我在我的资源中使用图标,但我需要动态地将它们作为图像添加到一些ToolStripMenuItem(s)。所以在我创建的方法中(这是下面的代码片段的来源),我必须将图标资源转换为位图,然后才能将它们添加到我的菜单项中。

string imageName = myImageNameStr;
imageName = imageName.Replace(" ", "_");
Icon myIcon = (Icon)Resources.ResourceManager.GetObject(imageName);
return myIcon.ToBitmap();

还有一点需要注意的是,如果你的图像/图标在其名称中有空格(" "),当你将它们添加到资源中时,VS会自动将这些空格替换为"_"(s)。因为,在命名资源时,空格不是有效字符。这就是为什么我在引用的代码中使用Replace()方法。你可以忽略这一行。

我查看了我的一个项目中的设计器代码,注意到它使用了这种符号

myButton.Image = global::MyProjectName.Properties.Resources.max;

其中max是我上传到项目中的资源的名称。

你需要从资源流中加载它。

Bitmap bmp = new Bitmap(
  System.Reflection.Assembly.GetEntryAssembly().
    GetManifestResourceStream("MyProject.Resources.myimage.png"));

如果你想知道程序集中的所有资源名称,请使用:

string[] all = System.Reflection.Assembly.GetEntryAssembly().
  GetManifestResourceNames();

foreach (string one in all) {
    MessageBox.Show(one);
}