Mizipzor
Mizipzor

Reputation: 52311

Convert System.Windows.Media.Imaging.BitmapSource to System.Drawing.Image

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?

Upvotes: 32

Views: 41477

Answers (2)

Rngbus
Rngbus

Reputation: 3101

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;
}

Upvotes: 16

John Gietzen
John Gietzen

Reputation: 49534

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;
}

Upvotes: 53

Related Questions