/// <summary> /// Converts a WPF's BitmapSource into a System.Drawing.Bitmap image. /// </summary> /// /// <param name="bitmapSource">The bitmap source to be converted.</param> /// public static Bitmap ToBitmap(this BitmapSource bitmapSource) { var format = bitmapSource.Format.ToImaging(); int width = bitmapSource.PixelWidth; int height = bitmapSource.PixelHeight; Bitmap bmp; if (bitmapSource.IsGrayscale()) { if (bitmapSource.Format != PixelFormats.Gray8) { return(new FormatConvertedBitmap(bitmapSource, PixelFormats.Gray8, BitmapPalettes.Gray256, 1.0).ToBitmap()); } bmp = Accord.Imaging.Image.CreateGrayscaleImage(width, height); } else { bmp = new Bitmap(width, height, format); } BitmapData data = bmp.LockBits(ImageLockMode.WriteOnly); bitmapSource.CopyPixels(Int32Rect.Empty, data.Scan0, data.Height * data.Stride, data.Stride); bmp.UnlockBits(data); return(bmp); }