title: How can I get a BitmapImage from a Resource?
body: <p>My assembly includes an image with BuildAction==Resource. I want to obtain a BitmapImage from this embedded resource.</p>
  <p>I can load a BitmapImage from file like this:</p>
  <pre><code>var bitmap = new BitmapImage(new Uri(path));
  </code></pre>
  <p>But how to I create a Uri that will refer to an embedded resource image?</p>
  <p>When I try and create a '<a href="https://docs.microsoft.com/en-us/dotnet/desktop/wpf/app-development/pack-uris-in-wpf" rel="nofollow noreferrer">pack URI</a>' (for example <code>pack://application:,,,/MyImage.png</code> or <code>pack://application:,,,/MyAssembly;component/MyImage.png</code>), an exception is thrown:</p>
  <p><strong>System.UriFormatException
  &quot;Invalid URI: A port was expected because of there is a colon (':') present but the port could not be parsed.&quot;</strong></p>
  <p>I found the fix,  to the UriFormatException in this <a href="https://web.archive.org/web/20091026154637/http://compilewith.net/2009/03/wpf-unit-testing-trouble-with-pack-uris.html" rel="nofollow noreferrer">blog post</a></p>
  <p>However, with that fix applied, I still get exceptions trying to load a BitmapImage from a pack URI.</p>
  <p>When using the <code>pack://application:,,,/Image.png</code> format, I get a NullReferenceException, and when using the <code>pack://application:,,,/AssemblyName;component/Image.png</code> format, I get a NotSupportedException &quot;The Uri prefix is not recognized&quot;.</p>
  <hr />
  <p><strong>Summary</strong>
  My problem was that I was trying to use a 'pack URI' in a process before any WPF control/window/etc had been instantiated, so the 'pack' URI scheme was not yet registered (other WPF required 'stuff' must also not be set too, because manually registering the pack scheme doesn't itself fix the problem). The solution was to wait until after instantiating my WPF usercontrol to use pack URIs.</p>