public
Last active

Bitmap <-> BitmapSource converter

  • Download Gist
BitmapFromBitmapSource.cs
C#
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28
public Bitmap GetBitmap(BitmapSource source)
{
Bitmap bmp = new Bitmap
(
source.PixelWidth,
source.PixelHeight,
System.Drawing.Imaging.PixelFormat.Format32bppPArgb
);
 
BitmapData data = bmp.LockBits
(
new System.Drawing.Rectangle(System.Drawing.Point.Empty, bmp.Size),
ImageLockMode.WriteOnly,
System.Drawing.Imaging.PixelFormat.Format32bppPArgb
);
 
source.CopyPixels
(
Int32Rect.Empty,
data.Scan0,
data.Height * data.Stride,
data.Stride
);
 
bmp.UnlockBits(data);
 
return bmp;
}
BitmapSourceFromBitmap.cs
C#
1 2 3 4 5 6 7 8 9 10 11 12
public BitmapSource GetBitmapSource(Bitmap bitmap)
{
BitmapSource bitmapSource = Imaging.CreateBitmapSourceFromHBitmap
(
bitmap.GetHbitmap(),
IntPtr.Zero,
Int32Rect.Empty,
BitmapSizeOptions.FromEmptyOptions()
);
 
return bitmapSource;
}

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.