简体   繁体   中英

Store Image in .resx as byte[] rather than Bitmap

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;

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

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

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[].

我不知道,虽然您可以重新定义.designer.cs中生成的代码,但不返回位图,而是返回包含Bitmap的字节数组。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM