#1,107 – Accessing an Embedded Resource Using a Uri

You can embed images into your WPF application as resources and then access them from code at run-time.

To embed an image as a resource, add it to your project and set its Build Action to Resource.

1107-001

You can now access this image at run-time using a Uri.  The URI for a simple resource just includes the path to the image.

In the example below, we use a URI to locate an image in the Images folder.

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                BitmapImage bmi = new BitmapImage(new Uri("pack://application:,,,/Images/Ted.jpg"));

                MessageBox.Show(string.Format("Image is {0}x{1} pixels", bmi.Width, bmi.Height));
            }
            catch (Exception xx)
            {
                MessageBox.Show(xx.ToString());
            }
        }

The pack://application portion of the Uri indicates that the resource is compiled into the current assembly.  The portion of the Uri after the third comma describes the path to the image.

1107-002

About Sean
Software developer in the Twin Cities area, passionate about software development and sailing.

2 Responses to #1,107 – Accessing an Embedded Resource Using a Uri

  1. Pingback: #1,110 – Using a Resource as a Content File | 2,000 Things You Should Know About WPF

  2. Pingback: #1,111 – Referencing Content Files from XAML | 2,000 Things You Should Know About WPF

Leave a comment