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


当前回答

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

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

其他回答

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

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

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

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

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

或者你可以在处理WPF或Silverlight时使用这一行,特别是当你已经在XAML标记中有源字符串时:

(ImageSource)new ImageSourceConverter().ConvertFromString(ImagePath);

ImagePath是这样的:

string ImagePath  = "/ProjectName;component/Resource/ImageName.png";

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

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

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

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