将System.Windows.Media.ImageSource转换为System.Drawing.Bitmap?

时间:2015-08-18 13:26:35

标签: c# wpf

我有一个System.Windows.Media.ImageSource类型的变量。我必须转换为System.Drawing.Bitmap。我无法找到适合我的解决方案。

是否可以使此行为有效?

1 个答案:

答案 0 :(得分:0)

这是一个适合您的解决方案:

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