GrayScale Image in WPF

The PixelFormats class is used to represent image pixel formats. The class has about 2 dozens of static properties representing various pixel formsts such as BlackWhite, Gray16, Gray32Float, Gray8, Rgba64 and so on.


To apply pixel formatting of an image, we use DestinationFormat property of FormatConvertedBitmap. The Source property of FormatConvertedBitmap is the original BitmapImage that you would like to convert to gray scale.


Listing 43 creates a FormatConvertedBitmap from a BitmapImage and sets its DestinationFormat to Gray8.


private void ConvertImageToGrayScaleImage()


    // Create an Image control

    Image grayImage = new Image();


    // Create a BitmapImage and sets its DecodePixelWidth and DecodePixelHeight

    BitmapImage bmpImage = new BitmapImage();


    bmpImage.UriSource = new Uri(@"C:\Images\Garden.jpg", UriKind.RelativeOrAbsolute);



    // Create a new image using FormatConvertedBitmap and set DestinationFormat to GrayScale

    FormatConvertedBitmap grayBitmap = new FormatConvertedBitmap();


    grayBitmap.Source = bmpImage;

    grayBitmap.DestinationFormat = PixelFormats.Gray8;



    // Set Source property of Image

    grayImage.Source = grayBitmap;





Listing 43

The output of Listing 43 generates Figure 47 which is a gray image.



Figure 47

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.