我的项目中有一张图像存储在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”。
其他回答
奇怪的是,通过对设计师的调查,我发现了一个更简单的方法:
该映像似乎可以从. properties . resources中获得。
我只是使用一个图像,因为我感兴趣的是将它粘贴到一个带有图像的控件中。
(Net 4.0, VS2010.)
和ImageBox命名为ImagePreview FormStrings。MyImageNames包含一个常规的get/set字符串强制转换方法,该方法链接到滚动框类型列表。 这些图像的名称与列表中的链接名称相同,除了.bmp结尾。 所有位图都被拖到resources.resx中
Object rm = Properties.Resources.ResourceManager.GetObject(FormStrings.MyImageNames);
Bitmap myImage = (Bitmap)rm;
ImagePreview.Image = myImage;
我在我的几个项目中使用的代码… 它假设您在资源中存储的图像仅为位图,而不是图标
public static Bitmap GetImageByName(string imageName)
{
System.Reflection.Assembly asm = System.Reflection.Assembly.GetExecutingAssembly();
string resourceName = asm.GetName().Name + ".Properties.Resources";
var rm = new System.Resources.ResourceManager(resourceName, asm);
return (Bitmap)rm.GetObject(imageName);
}
我建议:
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,…)
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);
推荐文章
- c#:如何获得一个字符串的第一个字符?
- String类中的什么方法只返回前N个字符?
- 在Android上调整一个大的位图文件到缩放输出文件
- 更好的方法将对象转换为int类型
- 我可以将c#字符串值转换为转义字符串文字吗?
- 在c#中转换char到int
- c#中朋友的对等物是什么?
- 关键字使用virtual+override vs. new
- 在ASP中选择Tag Helper。NET Core MVC
- 如何在没有任何错误或警告的情况下找到构建失败的原因
- 跨线程操作无效:控件“textBox1”从创建它的线程以外的线程访问
- 否ConcurrentList<T>在。net 4.0?
- 在c#中解析字符串为日期时间
- 由Jon Skeet撰写的《Singleton》澄清
- 自定义数字格式字符串始终显示符号