Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get resource as byte array in c#?

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.
enter image description here

Could anyone tell what's wrong there?
enter image description here

like image 630
Kosmo零 Avatar asked Oct 15 '25 03:10

Kosmo零


2 Answers

You need to set the file TestImg.png as an "Embedded Resource." The resource name would then be Resources/TestImg.png.

like image 73
Cole Tobin Avatar answered Oct 18 '25 05:10

Cole Tobin


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");
like image 26
Adola Avatar answered Oct 18 '25 07:10

Adola



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!