C# - 将 WPF Image.source 转换为 System.Drawing.Bitmap [英] C# - Convert WPF Image.source to a System.Drawing.Bitmap
问题描述
我发现很多人将 BitmapSource
转换为 Bitmap
,但是如何将 ImageSource
转换为 Bitmap
>?我正在制作一个成像程序,我需要从 Image
元素中显示的图像中提取位图.有人知道怎么做吗?
I've found loads of people converting a BitmapSource
to a Bitmap
, but what about ImageSource
to Bitmap
? I am making an imaging program and I need to extract bitmaps from the image displayed in the Image
element. Does anyone know how to do this?
编辑 1:
这是一个将BitmapImage
转换为Bitmap
的函数.请记住在编译器首选项中设置不安全"选项.
This is a function for converting the BitmapImage
to a Bitmap
. Remember to set the 'unsafe' option in the compiler preferences.
public static System.Drawing.Bitmap BitmapSourceToBitmap(BitmapSource srs)
{
System.Drawing.Bitmap btm = null;
int width = srs.PixelWidth;
int height = srs.PixelHeight;
int stride = width * ((srs.Format.BitsPerPixel + 7) / 8);
byte[] bits = new byte[height * stride];
srs.CopyPixels(bits, stride, 0);
unsafe
{
fixed (byte* pB = bits)
{
IntPtr ptr = new IntPtr(pB);
btm = new System.Drawing.Bitmap(width, height, stride, System.Drawing.Imaging.PixelFormat.Format1bppIndexed, ptr);
}
}
return btm;
}
接下来是获取BitmapImage
:
RenderTargetBitmap targetBitmap = new RenderTargetBitmap(
(int)inkCanvas1.ActualWidth,
(int)inkCanvas1.ActualHeight,
96d, 96d,
PixelFormats.Default);
targetBitmap.Render(inkCanvas1);
MemoryStream mse = new MemoryStream();
System.Windows.Media.Imaging.BmpBitmapEncoder mem = new BmpBitmapEncoder();
mem.Frames.Add(BitmapFrame.Create(targetBitmap));
mem.Save(mse);
mse.Position = 0;
BitmapImage bi = new BitmapImage();
bi.BeginInit();
bi.StreamSource = mse;
bi.EndInit();
接下来就是转换了:
Bitmap b = new Bitmap(BitmapSourceToBitmap(bi));
推荐答案
其实你不需要使用不安全的代码.有一个接受 IntPtr 的 CopyPixels
重载:
Actually you don't need to use unsafe code. There's an overload of CopyPixels
that accepts an IntPtr:
public static System.Drawing.Bitmap BitmapSourceToBitmap2(BitmapSource srs)
{
int width = srs.PixelWidth;
int height = srs.PixelHeight;
int stride = width * ((srs.Format.BitsPerPixel + 7) / 8);
IntPtr ptr = IntPtr.Zero;
try
{
ptr = Marshal.AllocHGlobal(height * stride);
srs.CopyPixels(new Int32Rect(0, 0, width, height), ptr, height * stride, stride);
using (var btm = new System.Drawing.Bitmap(width, height, stride, System.Drawing.Imaging.PixelFormat.Format1bppIndexed, ptr))
{
// Clone the bitmap so that we can dispose it and
// release the unmanaged memory at ptr
return new System.Drawing.Bitmap(btm);
}
}
finally
{
if (ptr != IntPtr.Zero)
Marshal.FreeHGlobal(ptr);
}
}
这篇关于C# - 将 WPF Image.source 转换为 System.Drawing.Bitmap的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!