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


当前回答

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

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

其他回答

奇怪的是,通过对设计师的调查,我发现了一个更简单的方法:

该映像似乎可以从. properties . resources中获得。

我只是使用一个图像,因为我感兴趣的是将它粘贴到一个带有图像的控件中。

(Net 4.0, VS2010.)

这是我如何从一个windows窗体应用程序的资源(.rc)文件创建一个ImageList:

ImageList imgList = new ImageList();

        var resourceSet = DataBaseIcons.ResourceManager.GetResourceSet(CultureInfo.CreateSpecificCulture("en-EN"), true, true);

        foreach (var r in resourceSet)
        {
            Logger.LogDebug($"Resource Type {((DictionaryEntry)r).Key.ToString()} is of {((DictionaryEntry)r).Value.GetType()}");
            
            if (((DictionaryEntry)r).Value is Bitmap)
            {
                imgList.Images.Add(((Bitmap)(((DictionaryEntry)r).Value)));
            }
            else
            {
                Logger.LogWarning($"Resource Type {((DictionaryEntry)r).Key.ToString()} is of type {((DictionaryEntry)r).Value.GetType()}");
            }
        }

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

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

JDS的回答效果最好。加载图像的c#示例:

包括图像作为资源(项目树->资源,右击添加所需的文件ImageName.png) 嵌入式资源(项目树->资源->ImageName.png,右键单击选择属性) .png文件格式(.bmp .jpg也可以)

pictureBox1。Image = ProjectName.Properties.Resources.ImageName;

注意以下几点:

资源映像文件为“ImageName.png”,文件扩展名应省略。 ProjectName也许可以更充分地理解为“程序集名称”,这将是Project->属性页面上各自的文本条目。

使用VisualStudio 2015 Community成功运行示例代码行。

比大多数提议的答案简单多了

tslMode.Image = global::ProjectName.Properties.Resources.ImageName;