C# - Convert WPF Image.source to a System.Drawing.Bitmap

前端 未结 4 1957
醉梦人生
醉梦人生 2020-11-29 09:35

I\'ve found loads of people converting a BitmapSource to a Bitmap, but what about ImageSource to Bitmap? I am making an i

4条回答
  •  甜味超标
    2020-11-29 09:47

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

提交回复
热议问题