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


当前回答

我建议:

System.Reflection.Assembly thisExe;
thisExe = System.Reflection.Assembly.GetExecutingAssembly();
System.IO.Stream file = 
    thisExe.GetManifestResourceStream("AssemblyName.ImageFile.jpg");
Image yourImage = Image.FromStream(file);

从msdn: http://msdn.microsoft.com/en-us/library/aa287676 (v = vs.71) . aspx

使用图像。FromStream更好,因为你不需要知道图像的格式(bmp, png,…)

其他回答

和ImageBox命名为ImagePreview FormStrings。MyImageNames包含一个常规的get/set字符串强制转换方法,该方法链接到滚动框类型列表。 这些图像的名称与列表中的链接名称相同,除了.bmp结尾。 所有位图都被拖到resources.resx中

Object rm = Properties.Resources.ResourceManager.GetObject(FormStrings.MyImageNames);
Bitmap myImage = (Bitmap)rm;
ImagePreview.Image = myImage;

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

Image myImage = Resources.myImage;

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

Bitmap bmp = new Bitmap(Resources.myImage);

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

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

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

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

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

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

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

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

这是我如何从一个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()}");
            }
        }