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.
Dim bitmap As 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.
Dim grayBitmapSource As 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 Sub GrayScaleButton_Click(ByVal sender As Object, ByVal e As RoutedEventArgs)
' Create a BitmapSource
Dim bitmap As New BitmapImage()
bitmap.BeginInit()
bitmap.UriSource = New Uri("C:\Books\Book WPF\How do I\ImageSample\ImageSample\Flower.JPG")
bitmap.EndInit()
' Create a FormatConvertedBitmap
Dim grayBitmapSource As 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
Dim grayImage As New Image()
grayImage.Width = 300
' Set Image source to new FormatConvertedBitmap
grayImage.Source = grayBitmapSource
' Add Image to Window
LayoutRoot.Children.Add(grayImage)
End Sub
How to Crop an Image in WPF?
CroppedBitmap is used to cropping an image. It takes a BitmapImage as source and a rectangle that you would like to crop.
The following code snippet crops and displays an image.
Private Sub CropImageButton_Click(ByVal sender As Object, ByVal e As RoutedEventArgs)
' Create a BitmapImage
Dim bitmap As New BitmapImage()
bitmap.BeginInit()
bitmap.UriSource = New Uri("C:\Books\Book WPF\How do I\ImageSample\ImageSample\Flower.JPG")
bitmap.EndInit()
' Create an Image
Dim croppedImage As New Image()
croppedImage.Width = 200
croppedImage.Margin = New Thickness(2)
' Create a CroppedBitmap from BitmapImage
Dim cb As New CroppedBitmap(DirectCast(bitmap, BitmapSource), New Int32Rect(20, 20, 100, 100))
' Set Image.Source to cropped image
croppedImage.Source = cb
' Add Image to Window
LayoutRoot.Children.Add(croppedImage)
End Sub