Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

.net

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?

like image 665
Mizipzor Avatar asked Sep 20 '10 13:09

Mizipzor


2 Answers

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;
}
like image 150
John Gietzen Avatar answered Nov 19 '22 07:11

John Gietzen


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;
}
like image 25
Rngbus Avatar answered Nov 19 '22 07:11

Rngbus