我的项目中有一张图像存储在Resources/myimage.jpg中。我如何动态加载这张图像到位图对象?
当前回答
或者你可以在处理WPF或Silverlight时使用这一行,特别是当你已经在XAML标记中有源字符串时:
(ImageSource)new ImageSourceConverter().ConvertFromString(ImagePath);
ImagePath是这样的:
string ImagePath = "/ProjectName;component/Resource/ImageName.png";
其他回答
你需要从资源流中加载它。
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()}");
}
}
在我的情况下——我在我的资源中使用图标,但我需要动态地将它们作为图像添加到一些ToolStripMenuItem(s)。所以在我创建的方法中(这是下面的代码片段的来源),我必须将图标资源转换为位图,然后才能将它们添加到我的菜单项中。
string imageName = myImageNameStr;
imageName = imageName.Replace(" ", "_");
Icon myIcon = (Icon)Resources.ResourceManager.GetObject(imageName);
return myIcon.ToBitmap();
还有一点需要注意的是,如果你的图像/图标在其名称中有空格(" "),当你将它们添加到资源中时,VS会自动将这些空格替换为"_"(s)。因为,在命名资源时,空格不是有效字符。这就是为什么我在引用的代码中使用Replace()方法。你可以忽略这一行。
我建议:
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,…)
最好的方法是将它们作为图像资源添加到项目的资源设置中。然后可以通过执行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是程序集中的任何类型。
推荐文章
- 检查字符串是否包含字符串列表中的元素
- 最好的方法在asp.net强制https为整个网站?
- 将字符串转换为System.IO.Stream
- 如何用OpenCV2.0和Python2.6调整图像大小
- 如何从枚举中选择一个随机值?
- 驻留在App_Code中的类不可访问
- 在链式LINQ扩展方法调用中等价于'let'关键字的代码
- dynamic (c# 4)和var之间的区别是什么?
- Visual Studio: ContextSwitchDeadlock
- 返回文件在ASP。Net Core Web API
- 自定义HttpClient请求头
- 如果我使用OWIN Startup.cs类并将所有配置移动到那里,我是否需要一个Global.asax.cs文件?
- VS2013外部构建错误"error MSB4019: The imported project <path> was not found"
- 从另一个列表id中排序一个列表
- 等待一个无效的异步方法