我的项目中有一张图像存储在Resources/myimage.jpg中。我如何动态加载这张图像到位图对象?
当前回答
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);
其他回答
你使用的是Windows窗体吗?如果你已经使用属性/资源UI添加了图像,你可以从生成的代码中访问图像,所以你可以简单地这样做:
var bmp = new Bitmap(WindowsFormsApplication1.Properties.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);
或者你可以在处理WPF或Silverlight时使用这一行,特别是当你已经在XAML标记中有源字符串时:
(ImageSource)new ImageSourceConverter().ConvertFromString(ImagePath);
ImagePath是这样的:
string ImagePath = "/ProjectName;component/Resource/ImageName.png";
在我的情况下——我在我的资源中使用图标,但我需要动态地将它们作为图像添加到一些ToolStripMenuItem(s)。所以在我创建的方法中(这是下面的代码片段的来源),我必须将图标资源转换为位图,然后才能将它们添加到我的菜单项中。
string imageName = myImageNameStr;
imageName = imageName.Replace(" ", "_");
Icon myIcon = (Icon)Resources.ResourceManager.GetObject(imageName);
return myIcon.ToBitmap();
还有一点需要注意的是,如果你的图像/图标在其名称中有空格(" "),当你将它们添加到资源中时,VS会自动将这些空格替换为"_"(s)。因为,在命名资源时,空格不是有效字符。这就是为什么我在引用的代码中使用Replace()方法。你可以忽略这一行。
我在我的几个项目中使用的代码… 它假设您在资源中存储的图像仅为位图,而不是图标
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);
}
推荐文章
- 实体框架核心:在上一个操作完成之前,在此上下文中开始的第二个操作
- 如何为构造函数定制Visual Studio的私有字段生成快捷方式?
- 如何使用JSON确保字符串是有效的JSON。网
- AppSettings从.config文件中获取值
- 通过HttpClient向REST API发布一个空体
- 如何检查IEnumerable是否为空或空?
- 自动化invokerrequired代码模式
- 在c#代码中设置WPF文本框的背景颜色
- 在c#中,什么是单子?
- c#和Java中的泛型有什么不同?和模板在c++ ?
- c#线程安全快速(est)计数器
- 如何将此foreach代码转换为Parallel.ForEach?
- 如何分裂()一个分隔字符串到一个列表<字符串>
- 如何转换列表<字符串>列表<int>?
- c#对象列表,我如何得到一个属性的和