C image controls windows system

Introduction

The <Image> element in XAML represents the Image control in WPF that is used to display images. We can also use the Image class in C# and WPF to create an Image control dynamically. The code example in this article shows how to view, stretch, rotate, and manipulate images in a WPF app using C#. 

The Image Class

The Image class in C# represents an image control in WPF that is used to load and display an image. The Image control displays .bmp, .gif, .ico, .jpg, .png, .wdp, and .tiff files. If a file is a multi frame image, only the first frame is displayed. The frame animation is not supported by the control.

The Source property of the Image class is the file an image displays. The Source property is a BitmapImage, that can be converted using the following code.

ImageViewer1.Source = new BitmapImage(new Uri("Creek.jpg", UriKind.Relative));  

In the preceding code snippet, UriKind lets you specify if the image is relative to the application path or has an absolute path.

I’ve created a WPF application with two labels, a button, and an Image control. The XAML code looks like this.

<StackPanel Orientation="Horizontal" Background="LightBlue" Height="40">  
    <Label Margin="10,0,0,0" Height="23" Name="Label1">  
        Current File:  
    </Label>  
    <Label Margin="5,0,0,0" Height="25" Name="FileNameLabel" Width="300" />  
    <Button Margin="5,0,0,0" Height="23" Name="BrowseButton" Width="75" Click="BrowseButton_Click">  
        Browse  
    </Button>                  
    </StackPanel>  
<StackPanel >  
    <Image Name="ImageViewer1" Height="400" Width="400" />         
</StackPanel>  

The application UI looks like this.

Figure 1

Now double clock on the Browse button and add an event handler. This is where we will browse a file on the computer using Windows File Dialog. The Browse button click event handler looks like the following: 

private void BrowseButton_Click(object sender, RoutedEventArgs e)  
{  
    OpenFileDialog dlg = new OpenFileDialog();  
    dlg.InitialDirectory = "c:\\";  
    dlg.Filter = "Image files (*.jpg)|*.jpg|All Files (*.*)|*.*";  
    dlg.RestoreDirectory = true;  
  
    if (dlg.ShowDialog() == System.Windows.Forms.DialogResult.OK)  
    {  
        string selectedFileName = dlg.FileName;  
        FileNameLabel.Content = selectedFileName;  
        BitmapImage bitmap = new BitmapImage();  
        bitmap.BeginInit();  
        bitmap.UriSource = new Uri(selectedFileName);  
        bitmap.EndInit();  
        ImageViewer1.Source = bitmap;  
    }  
}  

Click on the Browse button to browse the files, and the selected file will be displayed in the Viewer.

Figure 2

How to view an Image in WPF?

The Image element in XAML represents a WPF Image control and is used to display images in WPF. The Source property takes an image file that will be displayed by the Image control. The following code snippet shows the Flower.jpg file using an Image control.

<Image Source="Flower.jpg" />  

You can control the width and height of an image that is being displayed in the Image control by setting its Width and Height properties.

<Image Width="300" Height="200" Source="Flower.jpg" />  

One other way to set the Image.Source is by creating a BitmapImage. The following code snippet uses a BitmapImage created from a URI.

How to view an Image in WPF Dynamically?

The Image class in WPF represents an Image control. The following code snippet creates an Image control and sets its width, height, and Source properties.

How to stretch an Image in WPF using Image control?

The Stretch property of the Image describes how an image should be stretched to fill the destination rectangle. A value of Fill will cause your image to stretch to completely fill the output area. When the output area and the image have different aspect ratios, the image is distorted by this stretching. To make an Image preserve the aspect ratio of the image, set this property to Uniform, which is the default value of Stretch.

The StretchDirection property of Image describes how scaling applies to content and restricts the scaling to named axis types. It has three values UpOnly, DownOnly, and Both. The UpOnly value indicates that the image is scaled upward only when it is smaller than the parent. The DownOnly value indicates that the image is scaled downward when it is larger than the parent. Both value stretches the image to fit the parent.

The following code snippet sets Stretch and StretchDirection of an Image control.

How to rotate an Image in WPF?

The Rotation property of BitmapImage is used to rotate an image. It has the four values Rotate0, Rotate90, Rotate180 and Rotate270. The following code snippet rotates an image to 270 degrees.

How to apply grayscale on an Image in WPF?

The FormatConvertedBitmap is used to apply the formatting of images in WPF. The FormatConvertedBitmap.Source property is a BitmapImage that will be used in the formatting process.

This code creates a BitmapImage.

This code snippet creates a FormatConvertedBitmap from the BitmapImage created above.

The DestinationFormat property of FormatConvertedBitmap is used to apply formatting to images. The following code snippet sets the formatting of an image to Gray.

The complete source code looks like this.

How to crop an Image in WPF?

CroppedBitmap is used to crop an image. It takes a BitmapImage as the source and a rectangle that you would like to crop.

The following code snippet crops and displays an image.

private void CropImageButton_Click(object sender, RoutedEventArgs e)  
{  
    // Create a BitmapImage  
    BitmapImage bitmap = new BitmapImage();  
    bitmap.BeginInit();  
    bitmap.UriSource = new Uri(@"C:\Books\Book WPF\How do I\ImageSample\ImageSample\Flower.JPG");  
    bitmap.EndInit();  
  
    // Create an Image   
    Image croppedImage = new Image();  
    croppedImage.Width = 200;  
    croppedImage.Margin = new Thickness(2);  
  
    // Create a CroppedBitmap from BitmapImage  
    CroppedBitmap cb = new CroppedBitmap((BitmapSource)bitmap,   
        new Int32Rect(20, 20, 100, 100));        
    // Set Image.Source to cropped image  
    croppedImage.Source = cb;  
  
    // Add Image to Window  
    LayoutRoot.Children.Add(croppedImage);  
}  

This WPF article uses the Image control to display a picture. It displays JPG, PNG files with the BitmapImage type.

Image. How can we render a picture in a WPF program?

With an Image control, we display bitmaps of all types, including PNG and JPG. Other forms of images (drawings) are even supported. But this control have some complexity.

Based on:

.NET 4.5

Example. To begin, please create a WPF project and drag the Image control to your Window. Now edit the XAML markup for the Image element. Add a Loaded event handler by typing «Loaded». Visual Studio will create the Image_Loaded method.

In Image_Loaded, we want to assign the Source property of the Image object. This is a little tricky. We first create a BitmapImage object. We then assign the Source property to the BitmapImage reference.

BitmapImage: Using the BitmapImage requires some nuance. We must call BeginInit() before, and EndInit() after, setting the UriSource.

Warning: If you omit the BeginInit and EndInit calls, nothing will happen. If you don’t believe me, try it and find out.

Note: Please change the Uri object to point to a file that exists on your computer system.

Uri

Example markup: XAML

<Window x:Class="WpfApplication11.MainWindow"
	xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
	xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
	Title="MainWindow" Height="350" Width="525">
    <Grid>
	<Image
	    HorizontalAlignment="Left"
	    Height="100"
	    Margin="10,10,0,0"
	    VerticalAlignment="Top"
	    Width="100"
	    Loaded="Image_Loaded"/>
    </Grid>
</Window>

Example code: C#

using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media.Imaging;

namespace WpfApplication11
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
	public MainWindow()
	{
	    InitializeComponent();
	}

	private void Image_Loaded(object sender, RoutedEventArgs e)
	{
	    // ... Create a new BitmapImage.
	    BitmapImage b = new BitmapImage();
	    b.BeginInit();
	    b.UriSource = new Uri("c:\\plus.png");
	    b.EndInit();

	    // ... Get Image reference from sender.
	    var image = sender as Image;
	    // ... Assign Source.
	    image.Source = b;
	}
    }
}

Summary. Rarely are programs simple. But they tend to be composed of simple parts. And the Image type is also composed of simple parts. With it, we display pictures and other graphics—with a minimum of custom code.


Related Links

Adjectives
Ado
Ai
Android
Angular
Antonyms
Apache
Articles
Asp
Autocad
Automata
Aws
Azure
Basic
Binary
Bitcoin
Blockchain
C
Cassandra
Change
Coa
Computer
Control
Cpp
Create
Creating
C-Sharp
Cyber
Daa
Data
Dbms
Deletion
Devops
Difference
Discrete
Es6
Ethical
Examples
Features
Firebase
Flutter
Fs
Git
Go
Hbase
History
Hive
Hiveql
How
Html
Idioms
Insertion
Installing
Ios
Java
Joomla
Js
Kafka
Kali
Laravel
Logical
Machine
Matlab
Matrix
Mongodb
Mysql
One
Opencv
Oracle
Ordering
Os
Pandas
Php
Pig
Pl
Postgresql
Powershell
Prepositions
Program
Python
React
Ruby
Scala
Selecting
Selenium
Sentence
Seo
Sharepoint
Software
Spellings
Spotting
Spring
Sql
Sqlite
Sqoop
Svn
Swift
Synonyms
Talend
Testng
Types
Uml
Unity
Vbnet
Verbal
Webdriver
What
Wpf

Основные элементы управления:

Элемент WPF Image позволит выводить изображения в вашем приложении. Как вы убедитесь из данной главы, это очень гибкий элемент, со множеством опций и методов. Но сперва давайте рассмотрим наиболее общий пример встраивания изображения в окно WPF приложения.

<Image Source="https://upload.wikimedia.org/wikipedia/commons/3/30/Googlelogo.png" />

Результат будет выглядеть следующим образом:

Свойство Source, которое мы использовали в примере для указания изображения для вывода, вероятно одно из самых важных свойств данного элемента. Так что для начала давайте углубимся в эту тему.

Свойство Source

Как вы можете видеть из нашего примера, свойство Source позволяет легко указать какое именно изображение будет отображаться внутри элемента Image — в данном конкретном примере мы использовали изображение из удаленного источника, которое элемент Image автоматически подгрузит и отобразит сразу, как только оно станет доступным. Это отличный пример того, насколько гибким является элемент Image, но в большинстве случаев вы захотите иметь изображение в одном месте с вашим приложение, нежели загружать его из удаленного источника. Что, впрочем, может быть выполнено также легко!

Как вам возможно известно, вы можете добавлять ресурсы в ваш проект — они могут существовать в рамках вашего проекта в Visual Studio и быть видны в Solution Explorer наряду с другими файлами, относящимися к WPF (окна, пользовательские элементы управление и др.). Примером одного из таких фалов ресурсов и есть изображение, которое вы можете скопировать в соответствующую папку вашего проекта, чтобы добавить его. Впоследствии этот файл скомпилируется в ваше приложение (только если вы не укажете VS не делать этого) и может быть доступным по URL в формате для ресурсов.

<Image Source="/WpfTutorialSamples;component/Images/google.png" />

Такой URI, часто называемый «Pack URI’s«, большая тема со множеством нюансов, но пока лишь обратим внимание, что в сущности он (URI) состоит из двух частей:

  • Первой (/WpfTutorialSamples;component), где за именем сборки (WpfTutorialSamples в моём приложении) следует слово «component»
  • И второй, где указан относительный путь к файлу ресурса: /Images/google.png

Используя такой синтаксис, вы можете легко ссылаться на ресурсы, добавленные в ваше приложение. Для упрощения, WPF фрэймворк прочитает и простой, относительный URL — этого будет достаточно в большинстве случаев, до тех пор, пока вы не станете делать с ресурсами вашего приложения нечто усложненное. Вот как может выглядеть тот же код с использованием относительного URL:

<Image Source="/Images/google.png" />

Динамическая загрузка изображений (Code-behind)

Указание ресурса изображения прямо в XAML коде сработает во множестве случаев, но иногда вам понадобится загрузить картинку динамически, в зависимости от выбора пользователя. Это возможно сделать из застраничного кода (Code-behind). Вот пример того, как вы можете загрузить изображение находящееся на компьютере пользователя, основываясь на его выборе файла в диалоге OpenFileDialog:

private void BtnLoadFromFile_Click(object sender, RoutedEventArgs e)
{
    OpenFileDialog openFileDialog = new OpenFileDialog();
    if(openFileDialog.ShowDialog() == true)
    {
Uri fileUri = new Uri(openFileDialog.FileName);
imgDynamic.Source = new BitmapImage(fileUri);
    }
}

Заметьте как я создал объект класса BitmapImage, в который передал объект Uri, основанный на выбранном в диалоге пути файла. Мы можем использовать точно такой же прием, чтобы загрузить изображение, добавленное в приложение как ресурс:

private void BtnLoadFromResource_Click(object sender, RoutedEventArgs e)
{
    Uri resourceUri = new Uri("/Images/white_bengal_tiger.jpg", UriKind.Relative);
    imgDynamic.Source = new BitmapImage(resourceUri);    
}

Мы используем точно такой же относительный путь, который использовали в одном из предыдущих примеров, — просто убедитесь, что передали значение UriKind.Relative, когда создавали объект класса Uri, чтобы этот объект знал, что путь не абсолютный. Вот пример XAML кода и скриншот застраничного кода:

<Window x:Class="WpfTutorialSamples.Basic_controls.ImageControlCodeBehindSample"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:WpfTutorialSamples.Basic_controls"
mc:Ignorable="d"
Title="ImageControlCodeBehindSample" Height="300" Width="400">
    <StackPanel>
<WrapPanel Margin="10" HorizontalAlignment="Center">
    <Button Name="btnLoadFromFile" Margin="0,0,20,0" Click="BtnLoadFromFile_Click">Load from File...</Button>
    <Button Name="btnLoadFromResource" Click="BtnLoadFromResource_Click">Load from Resource</Button>
</WrapPanel>
<Image Name="imgDynamic" Margin="10"  />
    </StackPanel>
</Window>

Свойство Stretch

После свойства Source, которое является очевидно важным, думаю вторым наиболее интересным свойством элемента Image является свойство Stretch. Оно констролирует то, как ведет себя загруженное изображение, когда его размеры не совпадают с размерами элемента Image. Такое будет случатся постоянно, ведь размеры вашего окна могут меняться пользователем, только если его компоновка не статичная, что значит и размеры элемента(ов) Image будут также изменяться.

Как вы можете видеть из следующего примера, свойство Stretch может вносить заметную разницу в то, как отображается картинка:

<Window x:Class="WpfTutorialSamples.Basic_controls.ImageControlStretchSample"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:WpfTutorialSamples.Basic_controls"
mc:Ignorable="d"
Title="ImageControlStretchSample" Height="450" Width="600">
    <Grid>
<Grid.ColumnDefinitions>
    <ColumnDefinition Width="*" />
    <ColumnDefinition Width="*" />
    <ColumnDefinition Width="*" />
    <ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
    <RowDefinition Height="Auto" />
    <RowDefinition Height="*" />
</Grid.RowDefinitions>
<Label Grid.Column="0" HorizontalAlignment="Center" FontWeight="Bold">Uniform</Label>
<Label Grid.Column="1" HorizontalAlignment="Center" FontWeight="Bold">UniformToFill</Label>
<Label Grid.Column="2" HorizontalAlignment="Center" FontWeight="Bold">Fill</Label>
<Label Grid.Column="3" HorizontalAlignment="Center" FontWeight="Bold">None</Label>
<Image Source="/Images/white_bengal_tiger.jpg" Stretch="Uniform" Grid.Column="0" Grid.Row="1" Margin="5" />
<Image Source="/Images/white_bengal_tiger.jpg" Stretch="UniformToFill" Grid.Column="1" Grid.Row="1" Margin="5" />
<Image Source="/Images/white_bengal_tiger.jpg" Stretch="Fill" Grid.Column="2" Grid.Row="1" Margin="5" />
<Image Source="/Images/white_bengal_tiger.jpg" Stretch="None" Grid.Column="3" Grid.Row="1" Margin="5" />
    </Grid>
</Window>

Сложно поверить, но все четыре элемента Image отображают одно и то же изображение, но с разным значением свойства Stretch. Вот как работают различные режимы:

  • Uniform: Это режим по умолчанию. Изображение будет автоматически отмасштабировано так, чтобы оно целиком умещалось в элементе Image. Соотношение сторон изображения не изменится.
  • UniformToFill: Изображение будет отмасштабировано так, чтобы полностью заполнять элемент Image. Соотношение сторон также будет сохранено.
  • Fill: Изображение будет отмасштабировано так, чтобы заполнить весь элемент Image. Соотношение сторон может НЕ сохраниться потому, что высота и ширина изображения масштабируются независимо.
  • None: Если изоражение меньше элемента Image — никаких изменений не происходит. Если же оно больше — изображение будет подрезано так, чтобы умещаться в элементе Image, будет видна лишь часть изображения.

Заключение

Как показано в главе, элемент WPF Image позволяет вам легко отобразить картинку в вашем приложении будь-то из удаленного источника, встроенного ресурса или из локального расположения на компьютере.


This article has been fully translated into the following languages:

  • Catalan

  • Chinese

  • Czech

  • Danish

  • Dutch

  • French

  • German

  • Hebrew

  • Hungarian

  • Italian

  • Japanese

  • Polish

  • Portuguese

  • Russian

  • Spanish

  • Turkish

  • Ukrainian

  • Vietnamese

Is your preferred language not on the list? Click here to help us translate this article into your language!

Последнее обновление: 31.10.2015

Элемент Image

Элемент Image предназначен для работы с изображениями. Свойство Source позволяет задать путь к изображению, например:

<Image Source="myPhoto.jpg" />

WPF поддерживает различны форматы изображений: .bmp, .png, .gif, .jpg и т.д.

Также элемент позволяет проводить некоторые простейшие транформации с изображениями. Например, с помощью объекта FormatConvertedBitmap
и его свойства DestinationFormat можно получить новое изображение:

<Grid Background="Black">
    <Grid.ColumnDefinitions>
        <ColumnDefinition Width="2.5*" />
        <ColumnDefinition Width="*" />
    </Grid.ColumnDefinitions>
    <Image Grid.Column="0" x:Name="mainImage">
        <Image.Source>
            <FormatConvertedBitmap Source="3.jpg" 
				DestinationFormat="Gray32Float" />
        </Image.Source>
    </Image>
    <StackPanel Grid.Column="1">
        <Image Source="1.jpg" />
        <Image Source="2.jpg" />
        <Image Source="4.jpg" />
        <Image Source="3.jpg" />
    </StackPanel>
</Grid>

InkCanvas

InkCanvas представляет собой полотно, на котором можно рисовать. Первоначально оно предназначалось для стилуса, но в WPF есть поддержка также и для мыши
для обычных ПК. Его очень просто использовать:

<InkCanvas Background="LightCyan" />

Либо мы можем вложить в InkCanvas какое-нибудь изображение и на нем уже рисовать:

<InkCanvas>
    <Image Source="2.jpg"  Width="300" Height="250"  />
</InkCanvas>

Все рисование в итоге представляется в виде штрихов — элементов класса System.Windows.Ink.Stroke и хранится в коллекции Strokes,
определенной в классе InkCanvas.

Режим рисования

InkCanvas имеет несколько режимов, они задаются с помощью свойства EditingMode, значения для которого берутся из перечисления
InkCanvasEditingMode.. Эти значения бывают следующими:

  • Ink: используется по умолчанию и предполагает рисование стилусом или мышью

  • InkAndGesture: рисование с помощью мыши/стилуса, а также с помощью жестов (Up, Down, Tap и др.)

  • GestureOnly: рисование только с помощью жестов пользователя

  • EraseByStroke: стирание всего штриха стилусом

  • EraseByPoint: стирание только части штриха, к которой прикоснулся стилус

  • Select: выделение всех штрихов при касании

  • None: отсутствие какого-либо действия

Используя эти значения и обрабатывая события InkCanvas, такие как StrokeCollected (штрих нарисован), StrokeErased (штрих стерли) и др.,
можно управлять набором штрихов и создавать более функциональные приложения на основе InkCanvas.

WPF Image Control

With the help of the WPF image control, we can show the images in our application. WPF image control is a versatile control. WPF image control shows the image. For that, we can use either the ImageObject or the ImageBrush object. ImageObject will display the image, and the while the ImageBrushObject will paint another object with the use of the image. The source of the image is specified by referring to the image file, which supported the different formats.

Formats supported by the Image Control are as:

  1. Bitmap (BMP).
  2. Tagged Image File Format (TIFF).
  3. Icons (ICO).
  4. Joint Photography Expert Group (JPEG).
  5. Graphics Interchange Format (GIF).
  6. Portable Network Graphics (PNG).
  7. JPEG XR.

Properties used in Image Control

Sr. No. Properties Description
1. CanDrag CanDrag property is used to gets or sets the value. This value is used to indicate whether we can drag the element with the use of the drag-drop operation. CanDrag property is inherited from the User Interface element.
2. Height Height property is used to gets or sets the value. This value sets the height of the FrameworkElement.
3. PlayToSource PlayToSource property is used to get the transmitted information when we use the images for a PlayToSource Scenario.
4. SourceProperty the source property is used to identify the Source Dependency property.
5. Stretch Stretch property is used to Gets or sets the value, which shows how we can stretch the image to fill the destination.
6. StretchProperty StretchProperty is used to identify Search Dependency Property.
7. source the source property is used to gets or sets the source of the image.

Events used in Image Class

Events which we use in the Image class are as:

Sr. No. Properties Description
1. DataContextChanged DataContextChanged event will occur when the value of the property FrameworkElement.DataContext is changed.
2. DragEnter DragEnter event will occur when the input system reports the drag event with the element as a target.
3. DragLeave DragLeave event will occur when the input system reports the drag event with the elements like the origin.
4. DragStarting DragStarting event will occur when we initialize the drag operation.
5. ImageOpened ImageOpened event will occur when we download the source of the image and decode it without failure. We can use this event to determine the size of the image source.
6. ImageFailed ImageFailed event will occur when we retrieve the format of the image, and then an error will happen.
7. SizeChanged SizeChanged event will occur when the property of ActualHeight and ActualWidth is changing the value on the FrameworkElement.

WPF image control is a versatile control.

We will add the image by using the Syntax: Image Source property.

Source Property: We use Source Property to define the image which we want to display. We use source property inside the Image Control to identify the image which we want to display. We can easily define which image we want to show in the Image Control with the help of Source property.

Now we will take an example of the WPF Image Control.

Now let us create a new WPF project, and name of the project is given as WPFImageControl. Here we will divide the screen into the two rows by using the Grid.RowDefinition. Soon we will drag the three image controls. In the below example, we are going to show the three images. In the first, we are going to show a simple image. In the second image, we will set the opacity property. In the third image, we will set the image in the eclipse and paint it with the ImageBrush.

Now we will write code through which we will add the image.

MainWindow.XAML

After the compilation of the above code, we will get the below output:

OUTPUT

WPF Image Control

WPF image control is a versatile control.

We will add the image by using the Syntax: Image Source property.

Source Property: From the above example, we have seen that the Source Property is used to define the image we want to display. We use source property inside the Image Control to identify the image which we want to display. With the help of Source property, we can easily define the image which we want to show in the Image Control. In the above example, we used the remote image from which the image will automatically fetch and display the images as soon as possible. This feature shows how versatile the image control is, but in most situations, we want to bundle the images in our application instead of loading it from the remote source.

We can add resource files to our project. Resource files can be seen in the current visual studio and also can see the folder of the image in the solution explorer.

After that, we will compile our application. We can access the file by using the URL format for the resources, so if we have an image like “google.png” inside the folder “images”. Now the syntax will look like as shown below:

Syntax: <Image Source=” WpfTutorialSamples;component/Images/google.png”;

We will call these URI as the “Pack of URI’s”.

URI: URI contains two-part. First Part includes the assembly name which is “WPFTutorialSample” name of the application which we combined with the component. The Second Part includes the path of the resource, which is “/Images/google.png”.

By using this syntax, we can easily give a reference to the resources in our application. We can add the resource in our application by using the simple url like: <Image Source=”/Images/google.png”>.

Dynamic Loading of the Images

There are the situation arises when there is a need to load the image dynamically. For example, according to our choice, we want to load the images to the application. We can do it from the code.

For this, we will write a code to load the images from our computer which is based on our selection from the OpenFileDialog:

To show the data through the file, we will write the below code:

Here if we notice that we create the instance of the BitmapImage where I passed the URI. We will select it from our selected path. We will also use the same technique for loading the image, which includes the application as a resource.

For this as well, we will use the same relative path as we used above.

For the loading of the image from the different resources in our application, we will write the below code:

MainWindow.XAML

Now we will write the code for adding the image from the different resources on the clicking of the button.

MainWindow.XAML.cs

The output of the above code before the loading from the resource is shown below:

Output

WPF Image Control

If we click on the Load from File, this will open a new window where we will select the “Image,” which we want to show in our application. After clicking on the Load from File, a new window is open where we choose the file as shown in the below screenshot:

WPF Image Control

After clicking on “ok,” the image will look like as shown in the below screenshot:

WPF Image Control

Now we want to show the image through the resource file as shown in the below screenshot:

WPF Image Control

Stretch Property

As we know, the Source Property is important after that the second most important property is the Stretch Property. We will apply the stretch property when the loaded image doesn’t match with the dimension of the image control. The problem of the size unfitting will always happen because of the size of the window is controlled by others, and the size of the image control will also change.

With the help of the Stretch property, we can control the size of the image how they will look.

We will write a XAML code to define the view of the image by using the stretch property.

MainWindow.xaml

The output of the above code is as shown in the below screenshot:

WPF Image Control

Now we will explain the property of the Stretch:

Here we have seen that all the four of the images will show the same image but containing the different values of the stretch property.

Now we will explain the working of the various modes.

  • Uniform: Uniform is a default code. In uniform modes, the image will adjust itself to the area of the image. With the uniform modes, the image will set itself within the image area.
  • UniformToFill: In the UniformToFill modes, the images scaled itself so that the image can acquire all the area of the image.
  • Fill: Fill mode is used to fit itself according to the area of the image control. We cannot preserve the aspect ratio because we can independently scale the height and width of the image.
  • None: None mode is used in those scenarios when the size of the image is small. If the size of the image is small than the image control, then there is no need to do anything. If the size of the image is bigger than the image control now, the image will be cropped itself to fit itself into the image control, which means the one Part of the image will be displayed.

Wrap up

With the help of the WPF image control, we can easily display the image in our application. The resource of the image can be remote, embedded, or a local computer.


Понравилась статья? Поделить с друзьями:
0 0 голоса
Рейтинг статьи
Подписаться
Уведомить о
guest

0 комментариев
Старые
Новые Популярные
Межтекстовые Отзывы
Посмотреть все комментарии
  • Параллельный порт pci драйвер windows 7
  • Windows не удалось найти драйвер для сетевого адаптера обнаружено
  • Как открыть мой компьютер через cmd windows 10
  • Код ошибки 0x80072ee7 при обновлении windows 7 до windows 10
  • Как посмотреть системные требования компьютера на windows 11