c# - BitmapSource 和 Bitmap 之间有什么好的转换方法吗?

标签 c# .net wpf bitmap bitmapsource

据我所知,从 BitmapSource 转换为 Bitmap 的唯一方法是通过不安全的代码...像这样(来自 Lesters WPF blog):

myBitmapSource.CopyPixels(bits, stride, 0);

unsafe
{
  fixed (byte* pBits = bits)
  {
      IntPtr ptr = new IntPtr(pBits);

      System.Drawing.Bitmap bitmap = new System.Drawing.Bitmap(
        width,
        height,
        stride,
        System.Drawing.Imaging.PixelFormat.Format32bppPArgb,ptr);

      return bitmap;
  }
}

反之:

System.Windows.Media.Imaging.BitmapSource bitmapSource =
  System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap(
    bitmap.GetHbitmap(),
    IntPtr.Zero,
    Int32Rect.Empty,
    System.Windows.Media.Imaging.BitmapSizeOptions.FromEmptyOptions());

框架有没有更简单的方法?它不在那里的原因是什么(如果不是)?我认为它相当有用。

我需要它的原因是因为我使用 AForge 在 WPF 应用程序中执行某些图像操作。 WPF 想要显示 BitmapSource/ImageSource,但 AForge 在位图上工作。

最佳答案

可以通过使用 Bitmap.LockBits 将像素从 BitmapSource 直接复制到 Bitmap 而无需使用不安全代码/p>

Bitmap GetBitmap(BitmapSource source) {
  Bitmap bmp = new Bitmap(
    source.PixelWidth,
    source.PixelHeight,
    PixelFormat.Format32bppPArgb);
  BitmapData data = bmp.LockBits(
    new Rectangle(Point.Empty, bmp.Size),
    ImageLockMode.WriteOnly,
    PixelFormat.Format32bppPArgb);
  source.CopyPixels(
    Int32Rect.Empty,
    data.Scan0,
    data.Height * data.Stride,
    data.Stride);
  bmp.UnlockBits(data);
  return bmp;
}

关于c# - BitmapSource 和 Bitmap 之间有什么好的转换方法吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2284353/

相关文章:

c# - 拆分字符串,以便所有 + 数据放入一个列表,而 - 数据放入另一个列表

c# - 如何通过可空字段查询Azure表存储?

c# - 如何在 WPF 和 ASP.NET MVC 应用程序之间共享最多的代码?

c# - Windows 服务 : using of BitmapEncoder or BitmapDecoder ends with «The operation completed successfully»

c# - 如何调整此 wpf 按钮的大小

c# - 如何使用 WPF 使 Windows 静音?

c# - 这是使用 NLog 登录到特定目标的正确方法吗?

c# - 如何在图像周围放置两个标签(动态地);右边和底部?

c# - 在 C# 中重用或处理自定义字体的有效方法

c# - 遍历根目录并获取其中的所有文件?