7

Slightly daft, but...

Is there a way to prevent Visual Studio treating a .jpg file in a .resx as a Bitmap so that I can access a byte[] property for the resource instead?

I just want:

byte[] myImage = My.Resources.MyImage;
T.S.
  • 18,195
  • 11
  • 58
  • 78
Grokodile
  • 3,881
  • 5
  • 33
  • 59
  • Is it going to hurt the performance of your app to do this? `ImageConverter converter = new ImageConverter(); return (byte[])converter.ConvertTo(img, typeof(byte[]));` – Ed S. Mar 28 '12 at 05:37

3 Answers3

9

Alternatively, right click on your .resx file and click "View Code".

Edit the XML resource item to use System.Byte[] like this:

<data name="nomap" type="System.Resources.ResXFileRef, System.Windows.Forms">
   <value>..\Resources\nomap.png;System.Byte[]</value>
</data>

Save and you should be able to use Byte[] instead of Bitmap

Brian Chavez
  • 8,048
  • 5
  • 54
  • 47
  • 1
    Note: do not confused with **Resource.Designer.cs** file, any change of type there will get you a run-time error. Do your type changes in **Resource.resx** file. – Yehuda G. Jan 31 '17 at 09:00
  • 1
    I had to use the full type `System.Byte[], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089` otherwise I received a `MissingMethodException` – chad.mellor Jul 18 '20 at 23:00
  • You should probably also re-generate the Resource.Designer.cs file, e.g. by changing the access modifier from public to internal and back. – Mike Rosoft Nov 27 '20 at 14:40
7

Try using an "Embedded Resource" instead

So lets say you have a jpg "Foo.jpg" in ClassLibrary1. Set the "Build Action" to "Embedded Resource".

Then use this code to get the bytes

byte[] GetBytes()
{
    var assembly = GetType().Assembly;
    using (var stream = assembly.GetManifestResourceStream("ClassLibrary1.Foo.jpg"))
    {
        var buffer = new byte[stream.Length];
        stream.Read(buffer, 0, (int) stream.Length);
        return buffer;
    }
}

Or, alternatively, if you want a more re-usable method

byte[] GetBytes(string resourceName)
{
    var assembly = GetType().Assembly;
    var fullResourceName = string.Concat(assembly.GetName().Name, ".", resourceName);
    using (var stream = assembly.GetManifestResourceStream(fullResourceName))
    {
        var buffer = new byte[stream.Length];
        stream.Read(buffer, 0, (int) stream.Length);
        return buffer;
    }
}

and call

 var bytes = GetBytes("Foo.jpg");
Simon
  • 33,714
  • 21
  • 133
  • 202
  • Yeah I think this is what I want really, what I'm after is a way to keep an assortment of files in an assembly so that I can create them from code rather than copying them to output at build time. – Grokodile Mar 28 '12 at 05:53
7

Give the jpeg file a different extension, such as "myfile.jpeg.bin". Visual studio should then treat it as binary file and the generated designer code will return byte[].

Richard Schneider
  • 34,944
  • 9
  • 57
  • 73