Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
BitmapSource To Bitmap Conversion
/// <summary>
/// Converts a bitmap source to a bitmap
/// Make sure to dispose the bitmap
/// </summary>
/// <param name="source"></param>
/// <returns></returns>
public static Bitmap BitmapSourceToBitmap(BitmapSource source)
{
if (source == null)
return null;
var pixelFormat = PixelFormat.Format32bppArgb; //Bgr32 default
if (source.Format == PixelFormats.Bgr24)
pixelFormat = PixelFormat.Format24bppRgb;
else if(source.Format == PixelFormats.Pbgra32)
pixelFormat = PixelFormat.Format32bppPArgb;
else if(source.Format == PixelFormats.Prgba64)
pixelFormat = PixelFormat.Format64bppPArgb;
Bitmap bmp = new Bitmap(
source.PixelWidth,
source.PixelHeight,
pixelFormat);
BitmapData data = bmp.LockBits(
new Rectangle(Point.Empty, bmp.Size),
ImageLockMode.WriteOnly,
pixelFormat);
source.CopyPixels(
Int32Rect.Empty,
data.Scan0,
data.Height * data.Stride,
data.Stride);
bmp.UnlockBits(data);
return bmp;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment