我的项目中有一张图像存储在Resources/myimage.jpg中。我如何动态加载这张图像到位图对象?
当前回答
JDS的回答效果最好。加载图像的c#示例:
包括图像作为资源(项目树->资源,右击添加所需的文件ImageName.png) 嵌入式资源(项目树->资源->ImageName.png,右键单击选择属性) .png文件格式(.bmp .jpg也可以)
pictureBox1。Image = ProjectName.Properties.Resources.ImageName;
注意以下几点:
资源映像文件为“ImageName.png”,文件扩展名应省略。 ProjectName也许可以更充分地理解为“程序集名称”,这将是Project->属性页面上各自的文本条目。
使用VisualStudio 2015 Community成功运行示例代码行。
其他回答
使用以下一种。我已经用Windows窗体的网格视图单元进行了测试。
Object rm = Properties.Resources.ResourceManager.GetObject("Resource_Image");
Bitmap myImage = (Bitmap)rm;
Image image = myImage;
名称为“Resource_Image”,可以从项目中找到。
在项目名称下,您可以找到Properties。扩大它。在那里您可以看到参考资料。resx文件。打开它。将文件名应用为“Resource_Image”。
你使用的是Windows窗体吗?如果你已经使用属性/资源UI添加了图像,你可以从生成的代码中访问图像,所以你可以简单地这样做:
var bmp = new Bitmap(WindowsFormsApplication1.Properties.Resources.myimage);
奇怪的是,通过对设计师的调查,我发现了一个更简单的方法:
该映像似乎可以从. properties . resources中获得。
我只是使用一个图像,因为我感兴趣的是将它粘贴到一个带有图像的控件中。
(Net 4.0, VS2010.)
你可以通过以下方式获取图像的引用:
Image myImage = Resources.myImage;
如果你想复制图像,你需要做以下操作:
Bitmap bmp = new Bitmap(Resources.myImage);
用完后别忘了把bmp处理掉。如果你在编译时不知道资源映像的名称,你可以使用资源管理器:
ResourceManager rm = Resources.ResourceManager;
Bitmap myImage = (Bitmap)rm.GetObject("myImage");
ResourceManager的好处是你可以在Resources。myImage通常超出作用域,或者在您想动态访问资源的位置。此外,这适用于声音,配置文件等。
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);
推荐文章
- 新建T()
- 如何将枚举绑定到WPF中的组合框控件?
- 拒绝访问该路径
- Visual Studio - Resx文件默认“内部”为“公共”
- 使用linq转换列表到字典,不用担心重复
- 单元测试:日期时间。现在
- 什么是回调?
- 返回匿名类型的结果?
- 何时使用IList,何时使用List
- ConfigurationManager。AppSettings在.NET Core 2.0中可用?
- 在c#的控制台应用程序中使用'async
- 在单元测试中设置HttpContext.Current.Session
- 如何开始开发Internet Explorer扩展?
- 更新行,如果它存在,否则插入逻辑实体框架
- 在什么情况下SqlConnection会自动被征召到环境事务范围事务中?