load resource as byte array programmatically

2019-01-19 12:18发布

问题:

I added image as file and set type as resource (see screenshot) How do I pull it out as byte array without using resx files, etc?

回答1:

The process is described in How to embed and access resources by using Visual C#.

Essentially it requires use of reflection, using the Assembly class.

Stream imageStream = 
            currentAssembly.GetManifestResourceStream("Resources.logo_foot.png");

See How to convert an Stream into a byte[] in C#? for details of how to get a byte[] from a Stream.



回答2:

Things are even simpler than the item markes as answer!

If you click on the file in resources and view the properties window, you can set the File Type to binary. Then you can access the bytearray in code with a simple

var byteArray = Properties.Resources.FileName;

where FileName is the name of your resource.



回答3:

If you dont use the image directly (i.e: from a control if your project is a Windows App) then you could:

1- change the file extension (i.e: *.jpg.data)

2- add the "image" to a resource file RESX

3- access the byte array using: Resources.PathToImages.ResxFileName.ImageName

Note: if you add the image with the extension unchanged the RESX compiler creates a Bitmap property instead of a byte[] property.



回答4:

If this is for a website you could base64 encode the image and add it as the src of an image element or in a background-image definition in the CSS:

http://www.motobit.com/util/base64-decoder-encoder.asp

Note This will remove the dependency of having the file stored on the server, which may be good or bad.