我的项目中有一个存储在Resources/myimage.jpg的图像。如何将此图像动态加载到Bitmap对象中?
你是否在使用Windows Forms呢?如果你是通过属性/资源UI添加图片的,那么你可以从生成的代码中访问到该图片,所以你可以简单地这样做:
var bmp = new Bitmap(WindowsFormsApplication1.Properties.Resources.myimage);
Image myImage = Resources.myImage;
如果您想要制作图像的副本,您需要执行以下操作:
Bitmap bmp = new Bitmap(Resources.myImage);
在使用完bmp后,请不要忘记将其销毁。如果您在编译时不知道资源图像的名称,可以使用资源管理器:
ResourceManager rm = Resources.ResourceManager;
Bitmap myImage = (Bitmap)rm.GetObject("myImage");
ResourceManager的好处是您可以在Resources.myImage通常超出范围或者您想动态访问资源的情况下使用它。此外,这也适用于声音、配置文件等。
Set
关键字。 - PetoMPP您需要从资源流中加载它。
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);
}
typeof(this).Assembly
来简写。 - Sri Harsha Chilakapatitypeof(this)
不起作用。this.GetType().Assembly
是最接近你所说的,但它是有风险的,因为它会捕捉到一个可能在不同程序集中的继承超类。 - John Gibbtypeof(this)
等同于 this.GetType()
,是这样吗? - Sri Harsha Chilakapatitypeof(this);
无法编译,会得到 Error 1 Type expected
错误。 - John Gibb比大多数提出的答案都要简单得多
tslMode.Image = global::ProjectName.Properties.Resources.ImageName;
Bitmap
对象,而不是一个 Image
对象。 - vapcguy最好的方法是在项目的资源设置中将它们添加为图像资源。然后,您可以通过使用 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));
其中MyTypeFromSameAssemblyAsResource是你程序集中的任何类型。
使用以下代码。我已经在 Windows 表格视图单元格中进行了测试。
Object rm = Properties.Resources.ResourceManager.GetObject("Resource_Image");
Bitmap myImage = (Bitmap)rm;
Image image = myImage;
“Resource_Image”资源的名称可以在项目中找到。
在项目的名称下,您可以找到“属性”。展开它。那里您可以看到“Resources.resx”文件。打开它。将您的文件名应用为“Resource_Image”。
我在多个项目中使用的代码... 它假定你仅将图像存储为位图而不是图标资源。
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);
}
JDS的回答最好。C#示例加载图像:
pictureBox1.Image = ProjectName.Properties.Resources.ImageName;
注意以下几点:
此示例代码行可在 VisualStudio 2015 Community 中成功运行。
我建议:
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/zh-cn/library/aa287676(v=vs.71).aspx
使用 Image.FromStream 更好,因为您不需要知道图像的格式(bmp、png 等)。
var bmp = Resources.ImageName;