I added image to my c# project from Project settings -> Resources
How can i get this image at runtime?
I trying this:
public byte[] GetResource(string ResourceName)
{
System.Reflection.Assembly asm = Assembly.GetEntryAssembly();
// list all resources in assembly - for test
string[] names = asm.GetManifestResourceNames(); //even here my TestImg.png is not presented
System.IO.Stream stream = asm.GetManifestResourceStream(ResourceName); //this return null of course
byte[] data = new byte[stream.Length];
stream.Read(data, 0, (int)stream.Length);
return data;
}
I call this function this way:
byte[] data = GetResource("TestImg.png");
But I see my image in Resources folder in project explorer.
Could anyone tell what's wrong there?
You need to set the file TestImg.png
as an "Embedded Resource." The resource name would then be Resources/TestImg.png
.
您可以使用Properties.Resources.TestImg
访问图像。
This works:
var info = Application.GetResourceStream(uri);
var memoryStream = new MemoryStream();
info.Stream.CopyTo(memoryStream);
return memoryStream.ToArray();
In additional, if you want to save the image to your drive:
var b =
new Bitmap(namespace.Properties.Resources.image_resouce_name);
b.Save("FILE LOCATION");
You can edit the Resources.resx file and change:
<data name="ResourceKey" type="System.Resources.ResXFileRef, System.Windows.Forms">
<value>..\Resources\Image.jpg;System.Drawing.Bitmap, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a</value>
</data>
to (replace the type and assembly definition after the file name):
<data name="ResourceKey" type="System.Resources.ResXFileRef, System.Windows.Forms">
<value>..\Resources\Image.jpg;System.Byte[], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</data>
Now you can access the image as byte array using Properties.Resources.ResourceKey
. I don't know if this can be done without manually editing the resource file.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.