Skip to content

Instantly share code, notes, and snippets.

@RickStrahl
Last active October 11, 2021 02:21
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save RickStrahl/fe395578bb0f95e63cb65011fc207fc1 to your computer and use it in GitHub Desktop.
Save RickStrahl/fe395578bb0f95e63cb65011fc207fc1 to your computer and use it in GitHub Desktop.
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