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


当前回答

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

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

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

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

其他回答

这是我如何从一个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()}");
            }
        }
this.toolStrip1 = new System.Windows.Forms.ToolStrip();
this.toolStrip1.Location = new System.Drawing.Point(0, 0);
this.toolStrip1.Name = "toolStrip1";
this.toolStrip1.Size = new System.Drawing.Size(444, 25);
this.toolStrip1.TabIndex = 0;
this.toolStrip1.Text = "toolStrip1";
object O = global::WindowsFormsApplication1.Properties.Resources.ResourceManager.GetObject("best_robust_ghost");

ToolStripButton btn = new ToolStripButton("m1");
btn.DisplayStyle = ToolStripItemDisplayStyle.Image;
btn.Image = (Image)O;
this.toolStrip1.Items.Add(btn);

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

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

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

(Net 4.0, VS2010.)

你可以通过以下方式获取图像的引用:

Image myImage = Resources.myImage;

如果你想复制图像,你需要做以下操作:

Bitmap bmp = new Bitmap(Resources.myImage);

用完后别忘了把bmp处理掉。如果你在编译时不知道资源映像的名称,你可以使用资源管理器:

ResourceManager rm = Resources.ResourceManager;
Bitmap myImage = (Bitmap)rm.GetObject("myImage");

ResourceManager的好处是你可以在Resources。myImage通常超出作用域,或者在您想动态访问资源的位置。此外,这适用于声音,配置文件等。

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

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

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

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