private static unsafe Bitmap ToIndexed(Bitmap source, PixelFormat format)
{
Rectangle rectangle = new Rectangle(0, 0, source.Width, source.Height);
Bitmap result = new Bitmap(source.Width, source.Height, format);
BitmapData sourceData = source.LockBits(rectangle,
ImageLockMode.ReadOnly, source.PixelFormat),
resultData = result.LockBits(rectangle,
ImageLockMode.WriteOnly, format);
int sourceFlags = sourceData.Stride * sourceData.Height,
resultFlags = resultData.Stride * resultData.Height;
byte* sourceBuffer = (byte*)sourceData.Scan0.ToPointer(),
resultBuffer = (byte*)resultData.Scan0.ToPointer();
int offset = sourceFlags / resultFlags;
for (int i = 0; i < sourceFlags; i++)
{
resultBuffer[i / offset] = sourceBuffer[i];
}
result.UnlockBits(resultData);
source.UnlockBits(sourceData);
return result;
}