To remove the alpha channel, you could use Bitmap.Clone
:
public static Bitmap RemoveAlphaChannel(Bitmap bitmap) {
var rect = new Rectangle(0, 0, bitmap.Width, bitmap.Height);
return bitmap.Clone(rect, PixelFormat.Format24bppRgb);
}
Another way is to lock the bits without the alpha channel and then copy the memory to a new bitmap:
public static Bitmap RemoveAlphaChannel(Bitmap bitmap) {
Rectangle rect = new Rectangle(0, 0, bitmap.Width, bitmap.Height);
Bitmap bitmapDest = (Bitmap)new Bitmap(bitmap.Width, bitmap.Height, PixelFormat.Format24bppRgb);
BitmapData data = bitmap.LockBits(rect, ImageLockMode.ReadOnly, PixelFormat.Format24bppRgb);
BitmapData dataDest = bitmapDest.LockBits(rect, ImageLockMode.WriteOnly, PixelFormat.Format24bppRgb);
NativeMethods.CopyMemory(dataDest.Scan0, data.Scan0, (uint)data.Stride * (uint)data.Height);
bitmap.UnlockBits(data);
bitmapDest.UnlockBits(dataDest);
return bitmapDest;
}
static class NativeMethods {
const string KERNEL32 = "Kernel32.dll";
[DllImport(KERNEL32)]
public extern static void CopyMemory(IntPtr dest, IntPtr src, uint length);
}
24bppRgb
. Other optimizations will probably involve pointer black magic andBitmap.LockBits
, and it may be best to ask for those types of optimizations on the main StackOverflow site. \$\endgroup\$ – Dan Lyons May 3 '16 at 17:41