很容易将System.Windows.Controls.Image的BitmapSource设置为System.Drawing.Bitmap类型的变量,但如何将将System.Windows.Controls.Image的BitmapSource转换为System.Drawing.Bitmap的问题让我郁闷了半天,终于在网上找到了一个方法,虽然笨了点,不过总算实现了转换。不知道还有没有更好的方法,以后再研究研究。
Code
/// <summary>
/// 将System.Windows.Controls.Image的BitmapSource转换为System.Drawing.Bitmap
/// </summary>
/// <param name="image"></param>
/// <returns></returns>
private System.Drawing.Bitmap GetBitmap(System.Windows.Controls.Image image)
{
System.Windows.Media.Imaging.BitmapSource transformedBitmapSource = image.Source as BitmapSource;
int width = transformedBitmapSource.PixelWidth;
int height = transformedBitmapSource.PixelHeight;
int stride = width * ((transformedBitmapSource.Format.BitsPerPixel + 7) / 8);
byte[] bits = new byte[height * stride];
transformedBitmapSource.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;
}
}
}
需要更改工程的属性,在工程属性\"生成" 选中 “允许不安全代码”