有没有到的BitmapSource和位图之间转换的好办法? [英] Is there a good way to convert between BitmapSource and Bitmap?

查看:903
本文介绍了有没有到的BitmapSource和位图之间转换的好办法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

据我可以告诉从的BitmapSource转换为位图的唯一途径就是通过不安全code ......像这样(从的Lesters WPF博客):

As far as I can tell the only way to convert from BitmapSource to Bitmap is through unsafe code... Like this (from 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());

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

Is there an easier way in the framework? And what is the reason it isn't in there (if it's not)? I would think it's fairly usable.

我需要它的原因是因为我使用AForge在一个WPF应用程序做一定的图像操作。 WPF要展示的BitmapSource / ImageSource的,但AForge适用于位图。

The reason I need it is because I use AForge to do certain image operations in an WPF app. WPF wants to show BitmapSource/ImageSource but AForge works on Bitmaps.

推荐答案

这是可以做到不使用不安全的code。通过使用 Bitmap.LockBits 和复制从像素的BitmapSource 直奔位图

It is possible to do without using unsafe code by using Bitmap.LockBits and copy the pixels from the BitmapSource straight to the Bitmap

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

这篇关于有没有到的BitmapSource和位图之间转换的好办法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆