How do I construct a pack URI to an image that is in a resource file?
I have an assembly called MyAssembly.Resources.dll
, it has a folder called Ima
There are two ways to "embed" a resource in an assembly. Windows Forms uses the Embedded Resource
Build Action.
WPF expects resources contained in assemblies to be marked with the Resource
Build Action.
When you use the Resx editor in Visual Studio to add an image, it marks it as an Embedded Resource. Also, it stores it as type System.Drawing.Bitmap
. WPF expect a System.Windows.Media.ImageSource
type.
If you have a dissembler (like ILSpy) you can look at impact of setting different build actions on the files.
Sample ImagesLib project
Here is a screenshot of a project with two images. It's obvious from the names, the cat_embedded.jpg
is using the Embedded Resource
Build action and the cat_resource.jpg
is using the Resource
Build action.
This is what they look like in ILSpy.
See how the cat_resource.jpg file is within the ImageLib.g.resources section? That is where WPF looks for resources. The path to the file is part of the resource name (images/cat_resource.jpg
). So when you use a path like:
var uri = new Uri("pack://application:,,,/ImageLib;component/Images/cat_resource.jpg");
you specify the matching path after the word ;component
.
The other jpg file is located in a different location in the assembly, and uses periods in the name (ImageLib.Images.cat_embedded.jpg
).
You can try many permutations of that string to try and get the cat_embedded.jpg image, but WPF won't find it.
RESX Editor
Here's another project, that has two images, one marked as a resource and one added by the resx editor.
And here is the disassembled screenshot.
As you can see, the resx image is using the same URI location as the earlier embedded image example. It appears in your case, you are not going to be able to get the images from the resx file using the Pack URI.
Localization
From what you said in your question, what you are trying to accomplish is localization of the images right?
Have you looked at this MSDN article?
WPF Globalization and Localization Overview