我的项目中有一张图像存储在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,…)

其他回答

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

Image myImage = Resources.myImage;

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

Bitmap bmp = new Bitmap(Resources.myImage);

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

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

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

我建议:

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,…)

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

你也可以像这样在var中保存bmp:

var bmp = Resources.ImageName;

希望能有所帮助!

最好的方法是将它们作为图像资源添加到项目的资源设置中。然后可以通过执行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是程序集中的任何类型。