Sunday, August 22, 2010

WPF - Image Format Conversion (Including Gray Scaling)

In this post we will be discussing about how we can change the format of an image using XAML in WPF. The format conversion is performed using FormatConvertedBitmap. The destination formats are specified using DestinationFormat (dependency property) of FormatConvertedBitmap. It can be assigned various values from enumeration PixelFormats in System.Windows.Media namespace. Different pixel formats and their description can be found here:

http://msdn.microsoft.com/en-us/library/system.windows.media.pixelformats_members.aspx

Let's use the following image and see the effects of application of various formatting option on this. [This is night view of I.I.Chundrigar road @ Karachi].



To apply these formats to an image, we have to create a FormatConvertedBitmap instance in the relevant Resources section. We can apply different formatting options during initialization. We can then specify it as source of an image.

For our example, let us use three different Pixel formats and specify it to the same image as above. The XAML code of sample Window is as follows:

<Window x:Class="WPFComboBoxEditable.WindowGreyScale"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="WindowGreyScale">
<Window.Resources>
<BitmapImage UriSource="C:\Chundrigar.jpg" x:Key="image1" />
<FormatConvertedBitmap Source="{StaticResource image1}" x:Key="formattedImage" DestinationFormat="Gray32Float" />
<FormatConvertedBitmap Source="{StaticResource image1}" x:Key="formattedImage2" DestinationFormat="BlackWhite" />
<FormatConvertedBitmap Source="{StaticResource image1}" x:Key="formattedImage3" DestinationFormat="Cmyk32" />
</Window.Resources>
<Grid>
<ScrollViewer>
<StackPanel Orientation="Vertical">
<Image Source="{StaticResource image1}" Height="400" Width="400" />
<StackPanel Orientation="Horizontal" HorizontalAlignment="Center">
<Image Source="{StaticResource formattedImage}" Height="400" Width="400" />
<Image Source="{StaticResource formattedImage2}" Height="400" Width="400" />
<Image Source="{StaticResource formattedImage3}" Height="400" Width="400" />
</StackPanel>
</StackPanel>
</ScrollViewer>
</Grid>
</Window>


So we have created an instance of BitmapImage. Then we have created three different formatted images by applying different formats to the image. These formats include:
- Gray32Float
- BlackWhite
- Cmyk32

Afterwards, we have specified these formatted images as image sources of Images. When we run the application, the window is displayed as follows:



By the way, Gray32Float format looks really cool on this image :)

No comments: