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

前端 未结 2 1917
后悔当初
后悔当初 2020-12-09 02:32

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.Dr

相关标签:
2条回答
  • 2020-12-09 03:03

    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;
    }
    
    0 讨论(0)
  • 2020-12-09 03:08
    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;
    }
    
    0 讨论(0)
提交回复
热议问题