title: Using WritePixels when using a writeable bitmap from a intptr to create a bitmap.
body: <p>Im currently trying to use writeablebitmap to take a <code>IntPtr</code> of a scan of images and turn each one into a <code>Bitmap</code>. Im wanting to use writeablebitmap because im having an issue with standard gdi
  <a href="https://stackoverflow.com/questions/130790/gdi-system-drawing-bitmap-gives-error-parameter-is-not-valid-intermittently">GDI+ System.Drawing.Bitmap gives error Parameter is not valid intermittently</a></p>
  
  <p>There is a method on a <code>WriteableBitmap</code> that called <code>WritePixels</code>
  <a href="http://msdn.microsoft.com/en-us/library/aa346817.aspx" rel="nofollow noreferrer">http://msdn.microsoft.com/en-us/library/aa346817.aspx</a></p>
  
  <p>Im not sure what I set for the buffer and the stride every example I find it shows the stride as 0 although that throws an error. When I set the stride to 5 the image appear black. I know this may not be the most efficient code but any help would be appreciated.</p>
  
  <pre><code>//create bitmap header
  bmi = new BITMAPINFOHEADER();
  
  //create initial rectangle
  Int32Rect rect = new Int32Rect(0, 0, 0, 0);
  
  //create duplicate intptr to use while in global lock
  dibhand = dibhandp;
  bmpptr = GlobalLock(dibhand);
  
  //get the pixel sizes
  pixptr = GetPixelInfo(bmpptr);
  
  //create writeable bitmap
  var wbitm = new WriteableBitmap(bmprect.Width, bmprect.Height, 96.0, 96.0, System.Windows.Media.PixelFormats.Bgr32, null);
  
  //draw the image
  wbitm.WritePixels(rect, dibhandp, 10, 0);
  
  //convert the writeable bitmap to bitmap
  var stream = new MemoryStream();
  
  var encoder = new JpegBitmapEncoder();
  encoder.Frames.Add(BitmapFrame.Create(wbitm));
  encoder.Save(stream);
  
  byte[] buffer = stream.GetBuffer();
  var bitmap = new System.Drawing.Bitmap(new MemoryStream(buffer));
  
  GlobalUnlock(dibhand);
  GlobalFree(dibhand);
  GlobalFree(dibhandp);
  GlobalFree(bmpptr);
  dibhand = IntPtr.Zero;
  
  return bitmap;
  </code></pre>