2013-04-01 82 views
2

我从项目设置中添加了图像到我的c#项目 - >资源
如何在运行时获取此图像?
我想这一点:如何获取资源在c#中的字节数组?

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; 
} 

我调用这个函数是这样的:

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

但我看到我的资源文件夹图像在Project Explorer中。
enter image description here

有人能说出那里有什么问题吗?
enter image description here

+0

为什么你投'stream.Length'到'int'?它已经是'int'了。 '.LongLength'返回一个'长'。 –

+0

我不知道如何,但对我来说Stream.Length是** long ** – Kosmos

回答

7

您需要将文件TestImg.png设置为“嵌入式资源”。资源名称将是Resources/TestImg.png

+0

TestImg.png甚至不会在asm.GetManifestResourceNames()中呈现;如果改变我搜索的资源名称,那么有什么不同呢?无论如何,我试过,没有运气 – Kosmos

+0

反正,你能告诉我们什么'asm.GetManifestResourceNames'返回?这将有所帮助。 –

+0

我更新了我的问题,列出了这个节目 – Kosmos

2

您可以通过Properties.Resources.TestImg访问图片。

+0

哇,这很容易,真的有用:哦,谢谢。太悲伤它不是在运行时 – Kosmos

+0

你想要显示这个图像的UI? – Ansari

+0

我想要的是通过使用数据协议在WebBrowser中显示此图像http://msdn.microsoft.com/en-us/library/cc848897(v=vs.85).aspx – Kosmos

2

这工作:

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

在额外的,如果你想将图像保存到您的驱动器:

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