#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

Advertisement