Last active
October 11, 2021 02:21
-
-
Save RickStrahl/fe395578bb0f95e63cb65011fc207fc1 to your computer and use it in GitHub Desktop.
BitmapSource To Bitmap Conversion
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/// <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