public static Bitmap CreateCopyOfBitmapPreservingColourDepth(Bitmap source)
{
Bitmap newImage = new Bitmap(source.Width, source.Height, source.PixelFormat);
Rectangle rect = new Rectangle(0, 0, source.Width, source.Height);
BitmapData sourceData = source.LockBits(rect, ImageLockMode.ReadOnly, source.PixelFormat);
BitmapData destData = newImage.LockBits(rect, ImageLockMode.WriteOnly, newImage.PixelFormat);
int sourceAddress = sourceData.Scan0.ToInt32();
int destAddress = destData.Scan0.ToInt32();
for (int y = 0; y < newImage.Height; y++)
{
Utilities.CopyMemory(new IntPtr(sourceAddress), new IntPtr(destAddress), destData.Stride);
sourceAddress += sourceData.Stride;
destAddress += destData.Stride;
}
source.UnlockBits(sourceData);
newImage.UnlockBits(destData);
if (source.PixelFormat == PixelFormat.Format8bppIndexed)
{
ColorPalette sourcePal = source.Palette;
ColorPalette destPal = newImage.Palette;
for (int i = 0; i < sourcePal.Entries.Length; i++)
{
destPal.Entries[i] = sourcePal.Entries[i];
}
// The palette needs to be re-set onto the bitmap to force it
// to update its internal storage of the colours
newImage.Palette = destPal;
}
return newImage;
}