Elentok's Blog

About me

WPF, ImageSource and Embedded Resources

Well, it took me a couple of hours, but I’ve finally made it! I managed to load an embedded image from a dll using WPF.

In Windows.Forms I would just add a resource to the resource file, and I was able to access the resource easily via Resources.{name_of_resource_here}, but in WPF this doesn’t help me, because I needed an ImageSource.

After googling around for some time I found Tamir Khason’s blog post about his loadResource method, but I was having trouble loading the image since I was trying to loading an image from a referenced assembly (from within the assembly to an image that was supposed to be a resource within the assembly).

I played with different Pack URIs, the first one I found that worked was this:

"pack://application:,,,/{AssemblyName};component/Images/MyImage.png"

This is way too ugly, very non-C# IMHO, so I kept on looking until I found a relative path that was a little better:

"/{AssemblyName};component/Images/MyImage.png"

This isn’t the prettiest piece of code I’ve seen, but it’s a little better (the first one is an absolute uri, where the second is a relative uri).

I later added this method to my WpfUtils class:

public static Image CreateImageFromPath(string path)
{
  Image image = new Image();
  image.Source= LoadResource<ImageSource>(path);
  image.Width = image.Source.Width;
  image.Height = image.Source.Height;
  return image;
}

Now, to load an image I can just use this one-liner:

Image image = CreateImageFromPath(
  "/{AssemblyName};component/Images/MyImage.png");
Next:Tired... ?