将System.Windows.Media.ImageSource转换为System.Drawing.Bitmap
本文关键字:System Drawing Bitmap 转换 ImageSource Windows Media | 更新日期: 2023-09-27 18:08:26
我有一个System.Windows.Media.ImageSource
类型的变量。我要把这个转化成System.Drawing.Bitmap
。我找不到任何适合我的解决办法。
有可能使这个行为工作吗?
这是您的解决方案:
public static Drawing.Bitmap GetBitmapFromImageSource(BitmapSource source) {
int width = source.PixelWidth;
int height = source.PixelHeight;
int stride = width * ((source.Format.BitsPerPixel + 7) / 8);
IntPtr ptr = IntPtr.Zero;
try
{
ptr = System.Runtime.InteropServices.Marshal.AllocHGlobal(height * stride);
source.CopyPixels(new Int32Rect(0, 0, width, height), ptr, height * stride, stride);
using (var bmp = new Drawing.Bitmap(width, height, stride, Drawing.Imaging.PixelFormat.Format1bppIndexed, ptr)) {
return new Drawing.Bitmap(bmp);
}
}
finally {
if (ptr != IntPtr.Zero) {
System.Runtime.InteropServices.Marshal.FreeHGlobal(ptr);
}
}
}