How can I get BitmapImage from a resource?

My build includes an image using BuildAction == Resource. I want to get BitmapImage from this inline resource.

I can load BitmapImage from a file as follows:

var bitmap = new BitmapImage(new Uri(path)); 

But how can I create a Uri that will reference an image of an embedded resource?

When I try to create a ' package URI (for example, pack://application:,,,/MyImage.png or pack://application:,,,/MyAssembly;component/MyImage.png ), an exception is thrown:

System.UriFormatException "Invalid URI: The port was expected due to a colon (": "), but the port could not be parsed."

I found a fix in UriFormatException in this post

However, when applying this hotfix, I still get exceptions trying to load BitmapImage from the package URI.

When using the format pack://application:,,,/Image.png I get a NullReferenceException exception, and when using the format pack://application:,,,/AssemblyName;component/Image.png I get a NotSupportedException exception. Uri prefix is ​​not recognized.




Summary My problem was that I was trying to use a "batch URI" in the process before any WPF / window / etc control was created, so the "pack" URI was not registered yet (other WPF requirements "stuff "you also don’t need to be installed, because manually registering the package scheme does not in itself fix the problem). The solution was to wait until we instantiated my WPF user control to use the package URI.

+34
resources wpf bitmapimage
May 13 '09 at 12:41
source share
1 answer

This MSDN page contains all the information you might want to know about a resource URI in WPF (often called package URIs). You will want to use relative URIs more often, so see Table 4 , which should be especially useful.

If you need a quick overview of resource URIs (packages), see this blog post . It shows that the syntax is really relatively simple:

 pack://application:,,,/ResourceFile.xaml pack://application:,,,/ReferencedAssembly;component/ResourceFile.xaml 

However, there are a few quirks for development (in my experience), so often it takes a little experimentation to find the right resource URI.

+20
May 13 '09 at 12:47
source share



All Articles