Thumbnail In WPF

Create a Thumbnail

The BitmapImage class is used to create a thumbnail in WPF. The DecodePixelWidth and DecodePixelHeight properties are used to set the size of the bitmap from an image and this bitmap can be displayed in an Image control.

The BitmapImage element in XAML represents a Bitmap Image control at design-time. The following code snippet creates a BitmapImage element and sets its DecodePixelWidth and DecodePixelHeight attributes.

  1. <Image Width="120" Height="120" HorizontalAlignment="Center">  
  2.     <Image.Source>  
  3.         <BitmapImage DecodePixelWidth="100" DecodePixelHeight="100" UriSource="Garden.jpg" />  
  4.     </Image.Source>  
  5. </Image>  

Listing 40 shows a Window with two Image controls. The first Image control displays an image in its original size and the second control displays its thumbnail size.

  1. <Window x:Class="ThumbnailSample.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="MainWindow" Height="350" Width="625">  
  2.     <Grid Margin="10,10,10,10" Name="LayoutRoot">  
  3.         <Image Source="Garden.jpg" HorizontalAlignment="Left" />  
  4.         <Border BorderBrush="Gray" BorderThickness="2" HorizontalAlignment="Right" Width="130" Height="130">  
  5.             <Image Width="120" Height="120" HorizontalAlignment="Center">  
  6.                 <Image.Source>  
  7.                     <BitmapImage DecodePixelWidth="100" DecodePixelHeight="100" UriSource="Garden.jpg" />  
  8.                 </Image.Source>  
  9.             </Image>  
  10.         </Border>  
  11.     </Grid>  
  12. </Window>  

Listing 40

The output of Listing 40 generates Figure 44 where the left side image is the original image and right side image is the thumbnail preview of the image.

Thumbnail Image
Figure 44

The code listed in Listing 41 creates a thumbnail at run-time by creating a BitmapImage object and setting its DecodePixelWidth and DecodePixelHeight properties.

  1. privatevoid CreateATyhumbnail() {  
  2.     // Create an Image control  
  3.     Image thumbnailImage = newImage();  
  4.     thumbnailImage.Width = 130;  
  5.     // Create a BitmapImage and sets its DecodePixelWidth and DecodePixelHeight  
  6.     BitmapImage bmpImage = newBitmapImage();  
  7.     bmpImage.BeginInit();  
  8.     bmpImage.UriSource = newUri(@ "Garden.jpg", UriKind.RelativeOrAbsolute);  
  9.     bmpImage.DecodePixelWidth = 120;  
  10.     bmpImage.DecodePixelHeight = 120;  
  11.     bmpImage.EndInit();  
  12.     // Set Source property of Image  
  13.     thumbnailImage.Source = bmpImage;  
  14.     LayoutRoot.Children.Add(thumbnailImage);  
  15. }  

Listing 41


Mindcracker
Founded in 2003, Mindcracker is the authority in custom software development and innovation. We put best practices into action. We deliver solutions based on consumer and industry analysis.