GrayScale Image in VB.NET
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.
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 Sub ConvertImageToGrayScaleImage()
' Create an Image control
Dim grayImage As New Image()
' Create a BitmapImage and sets its DecodePixelWidth and DecodePixelHeight
Dim bmpImage As 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
Dim grayBitmap As 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)
End Sub
Listing 43
The output of Listing 43 generates Figure 47 which is a gray image.

Figure 47