title: C# - Convert WPF Image.source to a System.Drawing.Bitmap
body: <p>I've found loads of people converting a <code>BitmapSource</code> to a <code>Bitmap</code>, but what about <code>ImageSource</code> to <code>Bitmap</code>? I am making an imaging program and I need to extract bitmaps from the image displayed in the <code>Image</code> element. Does anyone know how to do this?</p>
  
  <p>EDIT 1:</p>
  
  <p>This is a function for converting the <code>BitmapImage</code> to a <code>Bitmap</code>. Remember to set the 'unsafe' option in the compiler preferences.</p>
  
  <pre><code>public static System.Drawing.Bitmap BitmapSourceToBitmap(BitmapSource srs)
  {
      System.Drawing.Bitmap btm = null;
  
      int width = srs.PixelWidth;
  
      int height = srs.PixelHeight;
  
      int stride = width * ((srs.Format.BitsPerPixel + 7) / 8);
  
      byte[] bits = new byte[height * stride];
  
      srs.CopyPixels(bits, stride, 0);
  
      unsafe
      {
          fixed (byte* pB = bits)
          {
              IntPtr ptr = new IntPtr(pB);
  
              btm = new System.Drawing.Bitmap(width, height, stride, System.Drawing.Imaging.PixelFormat.Format1bppIndexed, ptr);
          }
      }
      return btm;
  }
  </code></pre>
  
  <p>Next is now to get a <code>BitmapImage</code>:</p>
  
  <pre><code>RenderTargetBitmap targetBitmap = new RenderTargetBitmap(
      (int)inkCanvas1.ActualWidth,
      (int)inkCanvas1.ActualHeight,
      96d, 96d,
      PixelFormats.Default);
  
  targetBitmap.Render(inkCanvas1);
  
  MemoryStream mse = new MemoryStream();
  System.Windows.Media.Imaging.BmpBitmapEncoder mem = new BmpBitmapEncoder();
  mem.Frames.Add(BitmapFrame.Create(targetBitmap));
  mem.Save(mse);
  
  mse.Position = 0;
  BitmapImage bi = new BitmapImage();
  bi.BeginInit();
  bi.StreamSource = mse;
  bi.EndInit();
  </code></pre>
  
  <p>Next is to convert it:</p>
  
  <pre><code>Bitmap b = new Bitmap(BitmapSourceToBitmap(bi));
  </code></pre>