Home >Backend Development >C++ >How Can I Dynamically Load Images in WPF?
Dynamic loading of images in WPF
WPF applications often need to load images from external resources at runtime. With the resources provided by the .NET framework, the process is very simple and straightforward.
Use the BitmapImage
class to load images at runtime. It provides a Source
attribute that accepts a Uri
or Stream
object. Therefore, you can specify image position in a variety of ways.
Use Uri
Uri
Image files can be referenced directly, regardless of their location. The following are several common Uri formats:
Uri("file://path/to/image.png")
Uri("http://server/image.png")
Uri("pack://application:,,,/AssemblyName;component/path/to/image.png")
Example of using Uri:
<code class="language-csharp">var uri = new Uri("pack://application:,,,/Bilder/sas.png"); var bitmap = new BitmapImage(uri); image1.Source = bitmap;</code>
Use Stream
If the image is provided as Stream
, you can use the following code:
<code class="language-csharp">using (var stream = new FileStream("path/to/image.png", FileMode.Open)) { var bitmap = new BitmapImage(); bitmap.BeginInit(); bitmap.StreamSource = stream; bitmap.EndInit(); image1.Source = bitmap; }</code>
Set image source
After creating the BitmapImage
object, you need to assign it to the Image
attribute of the Source
control in XAML. For example:
<code class="language-xml"><Image x:Name="image1" /></code>
<code class="language-csharp">image1.Source = bitmap;</code>
Other instructions:
Image.Stretch
attribute to control how an image appears within a given space. The above is the detailed content of How Can I Dynamically Load Images in WPF?. For more information, please follow other related articles on the PHP Chinese website!