<Runtime.CompilerServices.Extension> Public Function ToBitmap(ByVal bitmapSource As BitmapSource, ByVal pixelFormat As Imaging.PixelFormat) As Bitmap Dim width As Integer = bitmapSource.PixelWidth Dim height As Integer = bitmapSource.PixelHeight Dim stride As Integer = width * ((bitmapSource.Format.BitsPerPixel + 7) \ 8) Dim ptr As IntPtr = IntPtr.Zero Try ptr = Marshal.AllocCoTaskMem(height * stride) bitmapSource.CopyPixels(New Windows.Int32Rect(0, 0, width, height), ptr, height * stride, stride) Using bitmap = New Bitmap(width, height, stride, pixelFormat, ptr) Return New Bitmap(bitmap) End Using Finally If ptr <> IntPtr.Zero Then Marshal.FreeCoTaskMem(ptr) End Try End Function