简体   繁体   English

将图像存储在 .resx 中作为字节 [] 而不是位图

[英]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?有没有办法阻止 Visual Studio 将.resx.jpg文件视为位图,以便我可以访问资源的byte[]属性?

I just want:我只是想:

byte[] myImage = My.Resources.MyImage;

Alternatively, right click on your .resx file and click "View Code".或者,右键单击您的.resx文件,然后单击“查看代码”。

Edit the XML resource item to use System.Byte[] like this:编辑 XML 资源项以使用System.Byte[]如下所示:

<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保存,您应该可以使用Byte[]而不是Bitmap

Try using an "Embedded Resource" instead尝试使用“嵌入式资源”代替

So lets say you have a jpg "Foo.jpg" in ClassLibrary1.因此,假设您在 ClassLibrary1 中有一个 jpg“Foo.jpg”。 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".为 jpeg 文件指定不同的扩展名,例如“myfile.jpeg.bin”。 Visual studio should then treat it as binary file and the generated designer code will return byte[]. Visual Studio 应将其视为二进制文件,生成的设计器代码将返回 byte[]。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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