title: Create Bitmap from a byte array of pixel data
body: <p>This question is about how to read/write, allocate and manage the pixel data of a Bitmap.</p>
  
  <p>Here is an example of how to allocate a byte array (managed memory) for pixel data and creating a Bitmap using it: </p>
  
  <pre><code>Size size = new Size(800, 600);
  PixelFormat pxFormat = PixelFormat.Format8bppIndexed;
  //Get the stride, in this case it will have the same length of the width.
  //Because the image Pixel format is 1 Byte/pixel.
  //Usually stride = "ByterPerPixel"*Width
  </code></pre>
  
  <p>//But it is not always true. <a href="https://web.archive.org/web/20120330012542/http://bobpowell.net/lockingbits.htm" rel="nofollow noreferrer">More info at bobpowell</a>.</p>
  
  <pre><code>int stride = GetStride(size.Width, pxFormat);
  byte[] data = new byte[stride * size.Height];
  GCHandle handle = GCHandle.Alloc(data, GCHandleType.Pinned);
  Bitmap bmp = new Bitmap(size.Width, size.Height, stride,
               pxFormat, handle.AddrOfPinnedObject());
  
  //After doing your stuff, free the Bitmap and unpin the array.
  bmp.Dispose();
  handle.Free();
  
  public static int GetStride(int width, PixelFormat pxFormat)
  {
      //float bitsPerPixel = System.Drawing.Image.GetPixelFormatSize(format);
      int bitsPerPixel = ((int)pxFormat &gt;&gt; 8) &amp; 0xFF;
      //Number of bits used to store the image data per line (only the valid data)
      int validBitsPerLine = width * bitsPerPixel;
      //4 bytes for every int32 (32 bits)
      int stride = ((validBitsPerLine + 31) / 32) * 4;
      return stride;
  }
  </code></pre>
  
  <p>I thought that the Bitmap would make a copy of the array data, but it actually points to the same data. Was you can see:</p>
  
  <pre><code>Color c;
  c = bmp.GetPixel(0, 0);
  Console.WriteLine("Color before: " + c.ToString());
  //Prints: Color before: Color [A=255, R=0, G=0, B=0]
  data[0] = 255;
  c = bmp.GetPixel(0, 0);
  Console.WriteLine("Color after: " + c.ToString());
  //Prints: Color after: Color [A=255, R=255, G=255, B=255]
  </code></pre>
  
  <p><strong>Questions:</strong></p>
  
  <ol>
  <li><p>Is it safe to do create a bitmap from a byte[] array (managed memory) and free() the GCHandle? If it is not safe, Ill need to keep a pinned array, how bad is that to GC/Performance?</p></li>
  <li><p>Is it safe to change the data (ex: data[0] = 255;)?</p></li>
  <li><p>The address of a Scan0 can be changed by the GC? I mean, I get the Scan0 from a locked bitmap, then unlock it and after some time lock it again, the Scan0 can be different?</p></li>
  <li><p>What is the purpose of ImageLockMode.UserInputBuffer in the LockBits method? It is very hard to find info about that! MSDN do not explain it clearly!</p></li>
  </ol>
  
  <p><strong>EDIT 1: Some followup</strong></p>
  
  <ol>
  <li><p>You need to keep it pinned. Will it slow down the GC? <a href="https://stackoverflow.com/questions/17044063/how-much-gchandle-pinned-memory-objects-would-make-garbage-collector-slows-down">I've asked it here</a>. It depends on the number of images and its sizes. Nobody have gave me a quantitative answer. It seams that it is hard to determine. 
  You can also alloc the memory using Marshal or use the unmanaged memory allocated by the Bitmap.</p></li>
  <li><p>I've done a lot of test using two threads. As long as the Bitmap is locked it is ok. If the Bitmap is unlock, than it is not safe! <a href="https://stackoverflow.com/questions/17030264/read-and-write-directly-to-unlocked-bitmap-unmanaged-memory-scan0-lru-cache">My related post about read/write directly to Scan0</a>. Boing's answer "I already explained above why you are lucky to be able to use scan0 outside the lock. Because you use the original bmp PixelFormat and that GDI is optimized in that case to give you the pointer and not a copy. This pointer is valid until the OS will decide to free it. The only time there is a guarantee is between LockBits and UnLockBits. Period."</p></li>
  <li><p>Yeah, it can happen, but large memory regions are treated different by the GC, it moves/frees this large object less frequently. So it can take a while to GC move this array. <a href="http://blogs.msdn.com/b/dotnet/archive/2011/10/04/large-object-heap-improvements-in-net-4-5.aspx" rel="nofollow noreferrer">From MSDN</a>: "Any allocation greater than or equal to <code>85,000 bytes</code> goes on the <code>large object heap (LOH)</code>" ... "LOH is only collected during a generation 2 collection". .NET 4.5 have Improvements in LOH.</p></li>
  <li><p>This question have been answered by @Boing. But I'm going to admit. I did not fully understand it. So if <code>Boing</code> or someone else could <code>please clarify it</code>, I would be glad. By the way, Why I can't just <a href="https://stackoverflow.com/questions/17030264/read-and-write-directly-to-unlocked-bitmap-unmanaged-memory-scan0-lru-cache">directly read/write to Sca0 without locking</a>? => You should not write directly to Scan0 because Scan0 points to a copy of the Bitmap data made by the unmanaged memory (inside GDI). After unlock, this memory can be reallocate to other stuff, its not certain anymore that Scan0 will point to the actual Bitmap data. This can be reproduced getting the Scan0 in a lock, unlock, and do some rotate-flit in the unlocked bitmap. After some time, Scan0 will point to an invalid region and you will get an exception when trying to read/write to its memory location.</p></li>
  </ol>