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.BeginInit();
bmpImage.UriSource = new Uri(@"C:\Images\Garden.jpg", UriKind.RelativeOrAbsolute);
bmpImage.EndInit();
// Create a new
image using FormatConvertedBitmap and set DestinationFormat to GrayScale
FormatConvertedBitmap
grayBitmap = new FormatConvertedBitmap();
grayBitmap.BeginInit();
grayBitmap.Source = bmpImage;
grayBitmap.DestinationFormat = PixelFormats.Gray8;
grayBitmap.EndInit();
// Set Source
property of Image
grayImage.Source = grayBitmap;
LayoutRoot.Children.Add(grayImage);
}
Listing 43
The
output of Listing 43 generates Figure 47 which is a gray image.
Figure 47