[ACCEPTED]-C# - Convert WPF Image.source to a System.Drawing.Bitmap-bitmap
Accepted answer
Actually you don't need to use unsafe code. There's 1 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);
}
}
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
Are your ImageSource not a BitmapSource? If 6 your loading the images from files they 5 should be.
Reply to your comment:
Sounds like 4 they should be BitmapSource then, BitmapSource 3 is a subtype of ImageSource. Cast the ImageSource 2 to BitmapSource and follow one of those 1 blogposts.
You don't need a BitmapSourceToBitmap
method at all. Just do 2 the following after creating your memory 1 stream:
mem.Position = 0;
Bitmap b = new Bitmap(mem);
Source:
stackoverflow.com
More Related questions
Cookie Warning
We use cookies to improve the performance of the site. By staying on our site, you agree to the terms of use of cookies.