Using XAML Image in WPF

XAML Image in WPF

The attached project with this article is a simple Image Viewer that allows users to browse an image and display it in WPF and XAML.

The Image Class

The Image class is used to load and view an image in WPF. This class displays .bmp, .gif, .ico, .jpg, .png, .wdp and .tiff files. If a file is a multiframe image, only the first frame is displayed. The frame animation is not supported by this class.

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:

  1. 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 created a WPF application with two labels, a button and an Image control. The XAML code looks like this: 

 

  1. <StackPanel Orientation="Horizontal" Background="LightBlue" Height="40">  
  2.     <Label Margin="10,0,0,0" Height="23" Name="Label1">  
  3.         Current File:  
  4.     </Label>  
  5.     <Label Margin="5,0,0,0" Height="25" Name="FileNameLabel" Width="300" />  
  6.     <Button Margin="5,0,0,0" Height="23" Name="BrowseButton" Width="75" Click="BrowseButton_Click">  
  7.         Browse  
  8.     </Button>                  
  9.     </StackPanel>  
  10. <StackPanel >  
  11.     <Image Name="ImageViewer1" Height="400" Width="400" />         
  12. </StackPanel>  
The application UI looks like this.


Figure 1.

The Browse button click event handler looks like the following:
  1. private void BrowseButton_Click(object sender, RoutedEventArgs e)  
  2. {  
  3.     OpenFileDialog dlg = new OpenFileDialog();  
  4.     dlg.InitialDirectory = "c:\\";  
  5.     dlg.Filter = "Image files (*.jpg)|*.jpg|All Files (*.*)|*.*";  
  6.     dlg.RestoreDirectory = true;  
  7.   
  8.     if (dlg.ShowDialog() == System.Windows.Forms.DialogResult.OK)  
  9.     {  
  10.         string selectedFileName = dlg.FileName;  
  11.         FileNameLabel.Content = selectedFileName;  
  12.         BitmapImage bitmap = new BitmapImage();  
  13.         bitmap.BeginInit();  
  14.         bitmap.UriSource = new Uri(selectedFileName);  
  15.         bitmap.EndInit();  
  16.         ImageViewer1.Source = bitmap;  
  17.     }  
  18. }  
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.
  1. <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.
  1. <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.
  1. <Image Width="300">  
  2.     <Image.Source>  
  3.         <BitmapImage DecodePixelWidth="200"  UriSource="Flower.jpg" />  
  4.     </Image.Source>  
  5. </Image>  
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.
  1. private void CreateViewImageDynamically()  
  2. {  
  3.     // Create Image and set its width and height  
  4.     Image dynamicImage = new Image();  
  5.     dynamicImage.Width = 300;  
  6.     dynamicImage.Height = 200;  
  7.   
  8.     // Create a BitmapSource  
  9.     BitmapImage bitmap = new BitmapImage();  
  10.     bitmap.BeginInit();  
  11.     bitmap.UriSource = new Uri(@"C:\Books\Book WPF\How do I\ImageSample\ImageSample\Flower.JPG");  
  12.     bitmap.EndInit();  
  13.   
  14.     // Set Image.Source  
  15.     dynamicImage.Source = bitmap;  
  16.   
  17.     // Add Image to Window  
  18.     LayoutRoot.Children.Add(dynamicImage);  
  19. }  
How to stretch Image in WPF using Image control

The Stretch property of 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, that 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 the 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. The Both value stretches the image to fit the parent.

The following code snippet sets Stretch and StretchDirection of an Image control.
  1. private void CreateViewImageDynamically()  
  2. {  
  3.     // Create Image and set its width and height  
  4.     Image dynamicImage = new Image();  
  5.     dynamicImage.Stretch = Stretch.Fill;  
  6.     dynamicImage.StretchDirection = StretchDirection.Both;  
  7.     dynamicImage.Width = 300;  
  8.     dynamicImage.Height = 200;  
  9.   
  10.     // Create a BitmapSource  
  11.     BitmapImage bitmap = new BitmapImage();  
  12.     bitmap.BeginInit();  
  13.     bitmap.UriSource = new Uri(@"C:\Books\Book WPF\How do I\ImageSample\ImageSample\Flower.JPG");  
  14.     bitmap.EndInit();  
  15.   
  16.     // Set Image.Source  
  17.     dynamicImage.Source = bitmap;  
  18.      
  19.     // Add Image to Window  
  20.     LayoutRoot.Children.Add(dynamicImage);  
  21. }  
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.
  1. <Image Width="300">  
  2.     <Image.Source>  
  3.         <BitmapImage DecodePixelWidth="200"  UriSource="Flower.jpg" Rotation="Rotate180" />  
  4.     </Image.Source>  
  5. </Image>  
How to apply gray scale on an Image in WPF

The FormatConvertedBitmap is used to apply 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.
  1. BitmapImage bitmap = new BitmapImage();  
  2. bitmap.BeginInit();  
  3. bitmap.UriSource = new Uri(@"C:\Books\Book WPF\How do I\ImageSample\ImageSample\Flower.JPG");  
  4. bitmap.EndInit();  
This code snippet creates a FormatConvertedBitmap from the BitmapImage created above.
  1. FormatConvertedBitmap grayBitmapSource = new FormatConvertedBitmap();  
  2. grayBitmapSource.BeginInit();  
  3. grayBitmapSource.Source = bitmap;  
The DestinationFormat property of FormatConvertedBitmap is used to apply formatting to images. The follow code snippet sets the formatting of an image to Gray.
  1. grayBitmapSource.DestinationFormat = PixelFormats.Gray32Float;  
  2. grayBitmapSource.EndInit();  
The complete source code looks like this.
  1. private void GrayScaleButton_Click(object sender, RoutedEventArgs e)  
  2. {  
  3.     // Create a BitmapSource  
  4.     BitmapImage bitmap = new BitmapImage();  
  5.     bitmap.BeginInit();  
  6.     bitmap.UriSource = new Uri(@"C:\Books\Book WPF\How do I\ImageSample\ImageSample\Flower.JPG");  
  7.     bitmap.EndInit();  
  8.   
  9.     // Create a FormatConvertedBitmap  
  10.     FormatConvertedBitmap grayBitmapSource = new FormatConvertedBitmap();  
  11.   
  12.     // BitmapSource objects like FormatConvertedBitmap can only have their properties  
  13.     // changed within a BeginInit/EndInit block.  
  14.     grayBitmapSource.BeginInit();  
  15.   
  16.     // Use the BitmapSource object defined above as the source for this new   
  17.     // BitmapSource (chain the BitmapSource objects together).  
  18.     grayBitmapSource.Source = bitmap;  
  19.   
  20.     // Key of changing the bitmap format is DesitnationFormat property of BitmapSource.  
  21.     // It is a type of PixelFormat. FixelFormat has dozens of options to set   
  22.     // bitmap formatting.   
  23.     grayBitmapSource.DestinationFormat = PixelFormats.Gray32Float;  
  24.     grayBitmapSource.EndInit();  
  25.   
  26.     // Create a new Image  
  27.     Image grayImage = new Image();  
  28.     grayImage.Width = 300;  
  29.     // Set Image source to new FormatConvertedBitmap  
  30.     grayImage.Source = grayBitmapSource;  
  31.   
  32.     // Add Image to Window  
  33.     LayoutRoot.Children.Add(grayImage);  
  34.   
  35. }  
How to crop an Image in WPF

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

The following code snippet crops and displays an image.
  1. private void CropImageButton_Click(object sender, RoutedEventArgs e)  
  2. {  
  3.     // Create a BitmapImage  
  4.     BitmapImage bitmap = new BitmapImage();  
  5.     bitmap.BeginInit();  
  6.     bitmap.UriSource = new Uri(@"C:\Books\Book WPF\How do I\ImageSample\ImageSample\Flower.JPG");  
  7.     bitmap.EndInit();  
  8.   
  9.     // Create an Image   
  10.     Image croppedImage = new Image();  
  11.     croppedImage.Width = 200;  
  12.     croppedImage.Margin = new Thickness(2);  
  13.   
  14.     // Create a CroppedBitmap from BitmapImage  
  15.     CroppedBitmap cb = new CroppedBitmap((BitmapSource)bitmap,   
  16.         new Int32Rect(20, 20, 100, 100));        
  17.     // Set Image.Source to cropped image  
  18.     croppedImage.Source = cb;  
  19.   
  20.     // Add Image to Window  
  21.     LayoutRoot.Children.Add(croppedImage);  
  22. }  

Up Next
    Ebook Download
    View all
    Learn
    View all