title: Convert HBitmap to Bitmap preserving alpha channel
body: <p>I have been searching in <a href="https://www.google.com/search?sourceid=chrome&amp;ie=UTF-8&amp;q=convert%20Hbitmap%20to%20bitmap%20preserving%20alpha%20channel" rel="nofollow noreferrer">Google</a> and <a href="https://stackoverflow.com/search?q=convert%20from%20HBitmap%20to%20Bitmap%20alpha%20channel">Stack Overflow</a>, and I cannot find a working example.</p>
  
  <p>I need to convert a HBitmap to a Managed .NET bitmap, but the following code <strong>does not preserve the alpha channel</strong>.</p>
  
  <pre><code>    private static Bitmap GetBitmapFromHBitmap(IntPtr nativeHBitmap)
      {
          Bitmap bmp = Bitmap.FromHbitmap(nativeHBitmap);
          return bmp;
      }
  </code></pre>
  
  <p>I found <a href="https://stackoverflow.com/questions/4627376/use-native-hbitmap-in-c-sharp-while-preserving-alpha-channel-transparency">this answer in SO</a>, but it does not work for me, the example preserves the transparency, however it flips my image 180º in Y axis and also rotate it 180º. I don't know why.</p>
  
  <p>This <a href="https://stackoverflow.com/questions/335273/how-to-create-a-gdiplusbitmap-from-an-hbitmap-retaining-the-alpha-channel-inf">other example</a> seems to work, but it is C++</p>
  
  <p>Someone has this working in C#, and very important, without memory leaks?</p>
  
  <p>Thanks in advance.</p>
  
  <hr>
  
  <p><strong>EDIT</strong>: Regarding the comment from @Hans Passant, I use the following code to get the HBitmap (it's a shell call to get the thumbnail or icon from the OS (only Vista and Win7).</p>
  
  <pre><code>    private static IntPtr GetHBitmap(string fileName, int width, int height, ThumbnailOptions options)
      {
          IShellItem nativeShellItem;
          Guid shellItem2Guid = new Guid(IShellItem2Guid);
          int retCode = SHCreateItemFromParsingName(fileName, IntPtr.Zero, ref shellItem2Guid, out nativeShellItem);
  
          NativeSize nativeSize = new NativeSize();
          nativeSize.Width = width;
          nativeSize.Height = height;
  
          IntPtr hBitmap;
          HResult hr = ((IShellItemImageFactory)nativeShellItem).GetImage(nativeSize, options, out hBitmap);
  
          Marshal.ReleaseComObject(nativeShellItem);
  
          if (hr == HResult.Ok) return hBitmap;
  
          throw Marshal.GetExceptionForHR((int) hr);
      }
  </code></pre>