Applying gray scale on an Image in WPF


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

This code creates 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();

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

FormatConvertedBitmap grayBitmapSource = new FormatConvertedBitmap();

grayBitmapSource.BeginInit();

grayBitmapSource.Source = bitmap;

 The DestinationFormat property of FormatConvertedBitmap is used to apply formatting on images. The follow code snippet sets the formatting of an image to gray.

grayBitmapSource.DestinationFormat = PixelFormats.Gray32Float;   
grayBitmapSource.EndInit();

The complete source code looks like this.

private void GrayScaleButton_Click(object sender, RoutedEventArgs e)

{

    // Create a BitmapSource

    BitmapImage bitmap = new BitmapImage();

    bitmap.BeginInit();

    bitmap.UriSource = new Uri(@"C:\Books\Book WPF\How do I\ImageSample\ImageSample\Flower.JPG");

    bitmap.EndInit();

 

    // Create a FormatConvertedBitmap

    FormatConvertedBitmap grayBitmapSource = new FormatConvertedBitmap();

 

    // BitmapSource objects like FormatConvertedBitmap can only have their properties

    // changed within a BeginInit/EndInit block.

    grayBitmapSource.BeginInit();

 

    grayBitmapSource.Source = bitmap;

 

    // Key of changing the bitmap format is DesitnationFormat property of BitmapSource.

    // It is a type of PixelFormat. FixelFormat has dozens of options to set

    // bitmap formatting.

    grayBitmapSource.DestinationFormat = PixelFormats.Gray32Float;

    grayBitmapSource.EndInit();

 

    // Create a new Image

    Image grayImage = new Image();

    grayImage.Width = 300;

    // Set Image source to new FormatConvertedBitmap

    grayImage.Source = grayBitmapSource;

 

    // Add Image to Window

    LayoutRoot.Children.Add(grayImage);

 

}

Up Next
    Ebook Download
    View all
    Learn
    View all