IgorShare Thoughts and Ideas

Consulting and Training

WPF: Extracting BitmapImage from an attached resource in referenced assembly/library

Posted by Igor Moochnick on 01/07/2009

It was not that simple to find out what is a reference to a linked resource within an assembly. The biggest problem was to nail down the exact pack path to a resource. It becomes simple if you know the name of a specific assembly, but, in real life, the names are changing pretty often.

This is the solution to such a problem: find out what assembly your code is running in and then construct a pack path to it. Then update it with a relative resource path. Under “relative resource path” I mean the path to your resource relative to the project (.proj) file within the VS solution. For example: if you like to store your images under “ProjectFolder/Images” folder then the relative path to your resource will be  “Images/ImageName.png”.

Don’t forget that in WPF a linked resource should have a Resource build action (not Embedded Resource) !!!

Here is a procedure that does all the above and hides all the hustle:

private BitmapImage GetImage(string resourcePath)
{
    var image = new BitmapImage();

    string moduleName = this.GetType().Assembly.GetName().Name;
    string resourceLocation =
        string.Format("pack://application:,,,/{0};component/{1}", moduleName,
                      resourcePath);

    try
    {
        image.BeginInit();
        image.CacheOption = BitmapCacheOption.OnLoad;
        image.CreateOptions = BitmapCreateOptions.IgnoreImageCache;
        image.UriSource = new Uri(resourceLocation);
        image.EndInit();
    }
    catch (Exception e)
    {
        System.Diagnostics.Trace.WriteLine(e.ToString());
    }

    return image;
}
About these ads

One Response to “WPF: Extracting BitmapImage from an attached resource in referenced assembly/library”

  1. renz said

    Excellent. Struggling a little bit with these Pack Uri’s and in a bit of a rush as well which never helps. Thanks for this.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

 
Follow

Get every new post delivered to your Inbox.

%d bloggers like this: