简体   繁体   English

如何在c#中以字节数组的形式获取资源?

[英]How to get resource as byte array in c#?

I added image to my c# project from Project settings -> Resources我从项目设置 -> 资源向我的 c# 项目添加了图像
How can i get this image at runtime?如何在运行时获取此图像?
I trying this:我试试这个:

public byte[] GetResource(string ResourceName)
{
    System.Reflection.Assembly asm = Assembly.GetEntryAssembly();

    // list all resources in assembly - for test
    string[] names = asm.GetManifestResourceNames(); //even here my TestImg.png is not presented

    System.IO.Stream stream = asm.GetManifestResourceStream(ResourceName); //this return null of course

    byte[] data = new byte[stream.Length];

    stream.Read(data, 0, (int)stream.Length);

    return data;
}

I call this function this way:我这样调用这个函数:

byte[] data = GetResource("TestImg.png");

But I see my image in Resources folder in project explorer.但是我在项目资源管理器的资源文件夹中看到了我的图像。
在此处输入图片说明

Could anyone tell what's wrong there?谁能告诉那里有什么问题?
在此处输入图片说明

You need to set the file TestImg.png as an "Embedded Resource."您需要将文件TestImg.png设置为“嵌入式资源”。 The resource name would then be Resources/TestImg.png .资源名称将是Resources/TestImg.png

您可以使用Properties.Resources.TestImg访问图像。

This works:这有效:

    var info = Application.GetResourceStream(uri);
    var memoryStream = new MemoryStream();
    info.Stream.CopyTo(memoryStream);
    return memoryStream.ToArray();

In additional, if you want to save the image to your drive:此外,如果要将图像保存到驱动器:

    var b =
    new Bitmap(namespace.Properties.Resources.image_resouce_name);
    b.Save("FILE LOCATION");

You can edit the Resources.resx file and change:您可以编辑 Resources.resx 文件并更改:

  <data name="ResourceKey" type="System.Resources.ResXFileRef, System.Windows.Forms">
    <value>..\Resources\Image.jpg;System.Drawing.Bitmap, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a</value>
  </data>

to (replace the type and assembly definition after the file name): to(替换文件名后的类型和程序集定义):

  <data name="ResourceKey" type="System.Resources.ResXFileRef, System.Windows.Forms">
    <value>..\Resources\Image.jpg;System.Byte[], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
  </data>

Now you can access the image as byte array using Properties.Resources.ResourceKey .现在您可以使用Properties.Resources.ResourceKey以字节数组的形式访问图像。 I don't know if this can be done without manually editing the resource file.我不知道这是否可以在不手动编辑资源文件的情况下完成。

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

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