Kosmo零
Kosmo零

Reputation: 4151

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

Upvotes: 4

Views: 14391

Answers (4)

Mike Rosoft
Mike Rosoft

Reputation: 748

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>

Regenerate the .Designer.cs file, such as by opening the resources (.resx file) in the designer and changing its access type to internal and then back to public (or vice versa). 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.

Upvotes: 2

Adola
Adola

Reputation: 337

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");

Upvotes: 2

Sharique Hussain Ansari
Sharique Hussain Ansari

Reputation: 1456

You can access the image with Properties.Resources.TestImg.

Upvotes: 2

Cole Tobin
Cole Tobin

Reputation: 9425

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

Upvotes: 8

Related Questions