title: How to copy Bitmap pixels to other Bitmap preserving alpha transparency in C#?
body: <p>Could some rewrite the following function to use any <strong>optimized</strong> mechanism? I'm pretty sure that this is not the way to proceed, copying pixel by pixel.</p>
  
  <p>I have read about <a href="http://msdn.microsoft.com/en-us/library/dd183351%28v=vs.85%29.aspx" rel="nofollow noreferrer">AlphaBlend</a>, or <a href="http://msdn.microsoft.com/en-us/library/dd183370%28v=vs.85%29.aspx" rel="nofollow noreferrer">BitBlt</a>, but I'm not used to native code.</p>
  
  <pre><code>public static Bitmap GetAlphaBitmap(Bitmap srcBitmap)
  {
      Bitmap result = new Bitmap(srcBitmap.Width, srcBitmap.Height, PixelFormat.Format32bppArgb);
  
      Rectangle bmpBounds = new Rectangle(0, 0, srcBitmap.Width, srcBitmap.Height);
  
      BitmapData srcData = srcBitmap.LockBits(bmpBounds, ImageLockMode.ReadOnly, srcBitmap.PixelFormat);
  
      try
      {
          for (int y = 0; y &lt;= srcData.Height - 1; y++)
          {
              for (int x = 0; x &lt;= srcData.Width - 1; x++)
              {
                  Color pixelColor = Color.FromArgb(
                      Marshal.ReadInt32(srcData.Scan0, (srcData.Stride * y) + (4 * x)));
  
                  result.SetPixel(x, y, pixelColor);
              }
          }
      }
      finally
      {
          srcBitmap.UnlockBits(srcData);
      }
  
      return result;
  }
  </code></pre>
  
  <p><strong>IMPORTANT NOTE</strong>: The source image has a wrong pixel format (Format32bppRgb), so I need to adjust the alpha channel. This is the only mechanism that works for me.</p>
  
  <p>The reason why the src image has a wrong pixel format is explained <a href="https://stackoverflow.com/questions/4627376/use-native-hbitmap-in-c-sharp-while-preserving-alpha-channel-transparency">here</a>.</p>
  
  <p>I tried the following options without luck:</p>
  
  <ul>
  <li>Creating a new image and draw the src image using the Graphics.DrawImage from src. Did not preserve the alpha.</li>
  <li>Creating a new image using the Scan0 form src. Works fine, but has a problem when the GC dispose the src image (explained in this other <a href="https://stackoverflow.com/questions/9311838/why-gc-is-making-fail-the-following-code-snippet">post</a>);</li>
  </ul>
  
  <p>This solution is the only that really works, but I know that is not optimal. I need to know how to do it using the WinAPI or other optimal mechanism.</p>
  
  <p>Thank you very much!</p>