public static ColorPalette GetColorPalette(int nColors)
{
// Assume monochrome image.
PixelFormat bitscolordepth = PixelFormat.Format1bppIndexed;
ColorPalette palette; // The Palette we are stealing
Bitmap bitmap; // The source of the stolen palette
// Determine number of colors.
if (nColors > 2) bitscolordepth = PixelFormat.Format4bppIndexed;
if (nColors > 16) bitscolordepth = PixelFormat.Format8bppIndexed;
// Make a new Bitmap object to get its Palette.
bitmap = new Bitmap(1, 1, bitscolordepth);
palette = bitmap.Palette; // Grab the palette
bitmap.Dispose(); // cleanup the source Bitmap
return palette; // Send the palette back
}