Save image in .resx as byte [], not Bitmap

A little stupid, but ...

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

I just want to:

byte[] myImage = My.Resources.MyImage; 
+4
source share
4 answers

Try using the Embedded Resource instead.

So let's say you have jpg "Foo.jpg" in ClassLibrary1. Set "Build Action" to "Embedded Resource".

Then use this code to get 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 to use a more reusable 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"); 
+5
source

Give the jpeg file a different extension, for example, "myfile.jpeg.bin". Then Visual studio processes it as a binary file, and the generated constructor code returns byte [].

+5
source

Alternatively, right-click on the .resx file and click View Code.

Edit the XML resource element to use System.Byte[] as follows:

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

Save and you should use Byte[] instead of Bitmap

+3
source

In no way do I know, although you can override the generated code in .designer.cs to return not a bitmap, but an array of bytes from the contained Bitmap.

0
source

Source: https://habr.com/ru/post/1403808/


All Articles