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

前端 未结 4 1747
醉梦人生
醉梦人生 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);
        }
    }
    
    0 讨论(0)
  • 2020-11-29 09:54

    You don't need a BitmapSourceToBitmap method at all. Just do the following after creating your memory stream:

    mem.Position = 0;  
    Bitmap b = new Bitmap(mem);
    
    0 讨论(0)
  • 2020-11-29 09:56

    That example worked for me:

        public static Bitmap ConvertToBitmap(BitmapSource bitmapSource)
        {
            var width = bitmapSource.PixelWidth;
            var height = bitmapSource.PixelHeight;
            var stride = width * ((bitmapSource.Format.BitsPerPixel + 7) / 8);
            var memoryBlockPointer = Marshal.AllocHGlobal(height * stride);
            bitmapSource.CopyPixels(new Int32Rect(0, 0, width, height), memoryBlockPointer, height * stride, stride);
            var bitmap = new Bitmap(width, height, stride, PixelFormat.Format32bppPArgb, memoryBlockPointer);
            return bitmap;
        }
    
    0 讨论(0)
  • 2020-11-29 09:56

    Are your ImageSource not a BitmapSource? If your loading the images from files they should be.

    Reply to your comment:

    Sounds like they should be BitmapSource then, BitmapSource is a subtype of ImageSource. Cast the ImageSource to BitmapSource and follow one of those blogposts.

    0 讨论(0)
提交回复
热议问题