30

I'm tying together two libraries. One only gives output of type System.Windows.Media.Imaging.BitmapSource, the other only accepts input of type System.Drawing.Image.

How can this conversion be performed?

Drew Noakes
  • 300,895
  • 165
  • 679
  • 742
Mizipzor
  • 51,151
  • 22
  • 97
  • 138

2 Answers2

52
private System.Drawing.Bitmap BitmapFromSource(BitmapSource bitmapsource)
{
  System.Drawing.Bitmap bitmap;
  using (MemoryStream outStream = new MemoryStream())
  {
    BitmapEncoder enc = new BmpBitmapEncoder();
    enc.Frames.Add(BitmapFrame.Create(bitmapsource));
    enc.Save(outStream);
    bitmap = new System.Drawing.Bitmap(outStream);
  }
  return bitmap;
}
John Gietzen
  • 48,783
  • 32
  • 145
  • 190
14

This is an alternate technique that does the same thing. The accepted answer works, but I ran into problems with images that had alpha channels (even after switching to PngBitmapEncoder). This technique may also be faster since it just does a raw copy of pixels after converting to compatible pixel format.

public Bitmap BitmapFromSource(System.Windows.Media.Imaging.BitmapSource bitmapsource)
{
        //convert image format
        var src = new System.Windows.Media.Imaging.FormatConvertedBitmap();
        src.BeginInit();
        src.Source = bitmapsource;
        src.DestinationFormat = System.Windows.Media.PixelFormats.Bgra32;
        src.EndInit();

        //copy to bitmap
        Bitmap bitmap = new Bitmap(src.PixelWidth, src.PixelHeight, System.Drawing.Imaging.PixelFormat.Format32bppArgb);
        var data = bitmap.LockBits(new Rectangle(Point.Empty, bitmap.Size), System.Drawing.Imaging.ImageLockMode.WriteOnly, System.Drawing.Imaging.PixelFormat.Format32bppArgb);
        src.CopyPixels(System.Windows.Int32Rect.Empty, data.Scan0, data.Height * data.Stride, data.Stride);
        bitmap.UnlockBits(data);

        return bitmap;
}
Rngbus
  • 2,911
  • 3
  • 22
  • 17