wpf 如何对嵌入在程序集中的资源图像进行 Uri 引用?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/22664534/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to make Uri reference to a Resource image embedded in the assembly itself?
提问by André Santaló
In my assembly project I have a .png image which it's Build Action is set to Resource.
在我的组装项目中,我有一个 .png 图像,它的 Build Action 设置为 Resource。
Now I want to make the following:
现在我想做以下事情:
_myIcon = new BitmapImage(new Uri(**path to the image embedded on the assembly**));
I have looked into the examples in http://msdn.microsoft.com/en-us/library/aa970069(v=vs.110).aspxbut as far as I tried gives me "Invalid URI: The format of the URI could not be determined.". I don't think this should be a complicated matter, am I taking the wrong approach?
我查看了http://msdn.microsoft.com/en-us/library/aa970069(v=vs.110).aspx 中的示例,但据我尝试给出了“无效的 URI:URI 的格式”无法确定。”。我不认为这应该是一件复杂的事情,我采取了错误的方法吗?
回答by Sebastian
For me it worked with something like this
对我来说,它适用于这样的事情
String filename = this.GetType().Namespace + ".Resources.myimg.bmp";
//or String.Join if you like
_myIcon = Bitmap.FromStream(Assembly.GetExecutingAssembly()
.GetManifestResourceStream(filename))
So FromStream + GetManifestResourceStream should be the magic words
所以 FromStream + GetManifestResourceStream 应该是魔法词
回答by André Santaló
user1129870's answer is valid but doesn't produces a BitmapSource.
user1129870 的回答是有效的,但不会产生 BitmapSource。
The correct answer, given that I have a folder called Images and inside an Image with the Build Action set to Resource, should be:
考虑到我有一个名为 Images 的文件夹并且在一个 Image 中,并且 Build Action 设置为 Resource,正确答案应该是:
_myIcon = new BitmapImage(new Uri(@"Images\MyImage.png", UriKind.Relative));
In my particular case, the problem was that I was using /instead of \.
在我的特殊情况下,问题是我使用的是/而不是\。

