Friday, September 5, 2008

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”);

5 comments:

Danno said...

Just a note that you spelled applicateion incorrectly. Copy and paste really burned me :)

Danno said...

And obviously I just spelled it wrong in my comment as well :)

Thanks for the post btw, really saved me a lot of headaches

David Elentok said...

Oops :)
Ok, it's fixed, thanks for pointing it out! (I hope no one else got copy&paste burned...)

Unknown said...
This comment has been removed by the author.
wabash9000 said...

This was useful, but it still took me a very long time to get it to work. It needs to be mentioned that you need to set the 'Build Action' for the images to 'Resource'. This is done by clicking the file in the solution explorer and looking at it's properties. This will allow the image to work with WPF and Forms.