我的项目中有一张图像存储在Resources/myimage.jpg中。我如何动态加载这张图像到位图对象?
当前回答
你可以通过以下方式获取图像的引用:
Image myImage = Resources.myImage;
如果你想复制图像,你需要做以下操作:
Bitmap bmp = new Bitmap(Resources.myImage);
用完后别忘了把bmp处理掉。如果你在编译时不知道资源映像的名称,你可以使用资源管理器:
ResourceManager rm = Resources.ResourceManager;
Bitmap myImage = (Bitmap)rm.GetObject("myImage");
ResourceManager的好处是你可以在Resources。myImage通常超出作用域,或者在您想动态访问资源的位置。此外,这适用于声音,配置文件等。
其他回答
JDS的回答效果最好。加载图像的c#示例:
包括图像作为资源(项目树->资源,右击添加所需的文件ImageName.png) 嵌入式资源(项目树->资源->ImageName.png,右键单击选择属性) .png文件格式(.bmp .jpg也可以)
pictureBox1。Image = ProjectName.Properties.Resources.ImageName;
注意以下几点:
资源映像文件为“ImageName.png”,文件扩展名应省略。 ProjectName也许可以更充分地理解为“程序集名称”,这将是Project->属性页面上各自的文本条目。
使用VisualStudio 2015 Community成功运行示例代码行。
你可以通过以下方式获取图像的引用:
Image myImage = Resources.myImage;
如果你想复制图像,你需要做以下操作:
Bitmap bmp = new Bitmap(Resources.myImage);
用完后别忘了把bmp处理掉。如果你在编译时不知道资源映像的名称,你可以使用资源管理器:
ResourceManager rm = Resources.ResourceManager;
Bitmap myImage = (Bitmap)rm.GetObject("myImage");
ResourceManager的好处是你可以在Resources。myImage通常超出作用域,或者在您想动态访问资源的位置。此外,这适用于声音,配置文件等。
和ImageBox命名为ImagePreview FormStrings。MyImageNames包含一个常规的get/set字符串强制转换方法,该方法链接到滚动框类型列表。 这些图像的名称与列表中的链接名称相同,除了.bmp结尾。 所有位图都被拖到resources.resx中
Object rm = Properties.Resources.ResourceManager.GetObject(FormStrings.MyImageNames);
Bitmap myImage = (Bitmap)rm;
ImagePreview.Image = myImage;
这是我如何从一个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()}");
}
}
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》澄清
- 自定义数字格式字符串始终显示符号