6

Is there any way for converting WriteableBitmap to Bitmap in C# ?

GVillani82
  • 17,196
  • 30
  • 105
  • 172
  • @GeorgeJohnston BitmapImage is in the System.Windows.Media namespace. Bitmap is in the System.Drawing namespace. The methods to convert between the two are entirely different. – red_sky Jun 25 '13 at 13:12

1 Answers1

25

It's pretty straightforward, actually. Here's some code that should work. I haven't tested it and I'm writing it from the top of my head.

private System.Drawing.Bitmap BitmapFromWriteableBitmap(WriteableBitmap writeBmp)
{
  System.Drawing.Bitmap bmp;
  using (MemoryStream outStream = new MemoryStream())
  {
    BitmapEncoder enc = new BmpBitmapEncoder();
    enc.Frames.Add(BitmapFrame.Create((BitmapSource)writeBmp));
    enc.Save(outStream);
    bmp = new System.Drawing.Bitmap(outStream);
  }
  return bmp;
}

The WriteableBitmap inherits from a BitmapSource, which can be saved directly to a stream. Then, you build a Bitmap from this stream.

Timothy Groote
  • 8,614
  • 26
  • 52
red_sky
  • 834
  • 9
  • 17
  • As an aside, you'll need PresentationCore and WindowsBase for .Net 3.5. For .Net 4, you'll also need System.Xaml. Don't know why that is. I'm using these references in an Asp.NET application to generate QR codes for TOTP authentication. – Derreck Dean Mar 17 '15 at 19:56
  • For some operations, `Bitmap` requires the underlying stream to be open when the bitmap was created from a stream. For example, `bmp.Save(filename)` will not work. – Mike Rosoft May 27 '22 at 08:15