C#

Setting WPF image source in code

25 September 2026 · 5 min read

Setting WPF image source in code

Dynamically setting image sources in WPF applications offers developers a powerful tool for creating engaging and responsive user interfaces. Whether displaying images from a database, a web service, or local files, understanding how to manipulate image sources programmatically is essential for any WPF developer. This article explores various techniques for setting WPF image source in code, providing you with the knowledge to enhance your applications’ visual appeal and functionality.

Using a URI

One of the most common methods involves using a Uniform Resource Identifier (URI) to point to the image’s location. This approach is particularly useful when loading images from external resources or embedded resources within your project.

For example:

Image myImage = new Image(); BitmapImage bitmap = new BitmapImage(); bitmap.BeginInit(); bitmap.UriSource = new Uri("https://www.example.com/image.jpg", UriKind.Absolute); bitmap.EndInit(); myImage.Source = bitmap;This code snippet creates an Image control, initializes a BitmapImage, and sets its UriSource property to the URL of the image. The BeginInit and EndInit calls are crucial for proper image loading.

Loading from a File

When working with images stored locally, you can directly load them from a file path. This is straightforward using the BitmapImage class.

Consider this example:

BitmapImage bitmap = new BitmapImage(new Uri(@"C:\path\to\image.png", UriKind.RelativeOrAbsolute)); myImage.Source = bitmap;This simplifies the process, directly using the file path within the BitmapImage constructor. Remember to handle potential exceptions, such as FileNotFoundException, to ensure application robustness.

Setting Source from a Resource

Embedding images as resources within your project provides a convenient way to manage assets. To set an image source from a resource:

Uri resourceUri = new Uri("/Resources/my_image.jpg", UriKind.Relative); BitmapImage resourceBitmap = new BitmapImage(resourceUri); myImage.Source = resourceBitmap;This method accesses the image embedded in the “Resources” folder. Ensure the image’s “Build Action” is set to “Resource” in your project properties.

Data Binding

For more complex scenarios, data binding offers a powerful mechanism for dynamically updating the image source. This allows you to connect the image source to a property in your data model.

Here’s a simplified illustration:

<Image Source="{Binding ImagePath}" />In your view model, the ImagePath property would hold the path or URI to the image. Changes to this property automatically update the image displayed.

Best Practices and Troubleshooting

When setting WPF image sources programmatically, consider these best practices:

  • Handle potential exceptions gracefully, especially when loading from external resources or files.
  • Optimize image sizes for performance, particularly for web-based images.

If you encounter issues, examine the following:

  1. Verify the image path or URI is correct.
  2. Check the image’s build action if using resources.
  3. Ensure proper exception handling is in place.

Featured Snippet: Setting the Image.Source property dynamically requires using the BitmapImage class. Its UriSource property handles URLs, while the constructor accepts file paths or resource URIs.

Choosing the right method depends on your specific needs. For static images, embedding as a resource or using a relative file path might suffice. Dynamic content benefits from URI or data binding approaches. Learn more about image handling in WPF.

FAQ

Q: Why is my image not displaying?

A: Double-check the file path, URI, or resource settings. Also, ensure proper exception handling to catch any loading errors.

Mastering these techniques empowers you to create visually rich and dynamic WPF applications. By understanding the nuances of each method, you can select the optimal approach for your specific scenario. Experiment with these examples and explore further resources like the official Microsoft documentation (WPF Documentation) and Stack Overflow (WPF on Stack Overflow) to deepen your understanding. Leverage these tools and techniques to enhance the user experience and bring your WPF applications to life with compelling visuals. For deeper insights into WPF development, consider exploring advanced topics like image effects and custom controls. Continue learning and experimenting to unlock the full potential of WPF’s imaging capabilities. WPF Tutorial on Images offers a good starting point.

Question & Answer :
I’m trying to set a WPF image’s source in code. The image is embedded as a resource in the project. By looking at examples I’ve come up with the below code. For some reason it doesn’t work - the image does not show up.

By debugging I can see that the stream contains the image data. So what’s wrong?

Assembly asm = Assembly.GetExecutingAssembly(); Stream iconStream = asm.GetManifestResourceStream("SomeImage.png"); PngBitmapDecoder iconDecoder = new PngBitmapDecoder(iconStream, BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.Default); ImageSource iconSource = iconDecoder.Frames[0]; _icon.Source = iconSource; 

The icon is defined something like this: <Image x:Name="_icon" Width="16" Height="16" />

After having the same problem as you and doing some reading, I discovered the solution - Pack URIs.

I did the following in code:

Image finalImage = new Image(); finalImage.Width = 80; ... BitmapImage logo = new BitmapImage(); logo.BeginInit(); logo.UriSource = new Uri("pack://application:,,,/AssemblyName;component/Resources/logo.png"); logo.EndInit(); ... finalImage.Source = logo; 

Or shorter, by using another BitmapImage constructor:

finalImage.Source = new BitmapImage( new Uri("pack://application:,,,/AssemblyName;component/Resources/logo.png")); 

The URI is broken out into parts:

  • Authority: application:///

  • Path: The name of a resource file that is compiled into a referenced assembly. The path must conform to the following format: AssemblyShortName[;Version][;PublicKey];component/Path

    • AssemblyShortName: the short name for the referenced assembly.
    • ;Version [optional]: the version of the referenced assembly that contains the resource file. This is used when two or more referenced assemblies with the same short name are loaded.
    • ;PublicKey [optional]: the public key that was used to sign the referenced assembly. This is used when two or more referenced assemblies with the same short name are loaded.
    • ;component: specifies that the assembly being referred to is referenced from the local assembly.
    • /Path: the name of the resource file, including its path, relative to the root of the referenced assembly’s project folder.

The three slashes after application: have to be replaced with commas:

Note: The authority component of a pack URI is an embedded URI that points to a package and must conform to RFC 2396. Additionally, the “/” character must be replaced with the “,” character, and reserved characters such as “%” and “?” must be escaped. See the OPC for details.

And of course, make sure you set the build action on your image to Resource.