Is there a good way to convert between BitmapSource and Bitmap? Is there a good way to convert between BitmapSource and Bitmap? wpf wpf

Is there a good way to convert between BitmapSource and Bitmap?


It is possible to do without using unsafe code by using Bitmap.LockBits and copy the pixels from the BitmapSource straight to the Bitmap

Bitmap GetBitmap(BitmapSource source) {  Bitmap bmp = new Bitmap(    source.PixelWidth,    source.PixelHeight,    PixelFormat.Format32bppPArgb);  BitmapData data = bmp.LockBits(    new Rectangle(Point.Empty, bmp.Size),    ImageLockMode.WriteOnly,    PixelFormat.Format32bppPArgb);  source.CopyPixels(    Int32Rect.Empty,    data.Scan0,    data.Height * data.Stride,    data.Stride);  bmp.UnlockBits(data);  return bmp;}


You can just use these two methods:

public static BitmapSource ConvertBitmap(Bitmap source){    return System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap(                  source.GetHbitmap(),                  IntPtr.Zero,                  Int32Rect.Empty,                  BitmapSizeOptions.FromEmptyOptions());}public static Bitmap BitmapFromSource(BitmapSource bitmapsource){    Bitmap bitmap;    using (var outStream = new MemoryStream())    {        BitmapEncoder enc = new BmpBitmapEncoder();        enc.Frames.Add(BitmapFrame.Create(bitmapsource));        enc.Save(outStream);        bitmap = new Bitmap(outStream);    }    return bitmap;}

It works perfectly for me.


Is this what your looking for?

Bitmap bmp = System.Drawing.Image.FromHbitmap(pBits);