예제 #1
0
        public static Palette CalculatePalette(Bitmap img, int paletteSize)
        {
            Palette palette         = new Palette();
            Palette lastGoodPalette = null;

            // sanity check
            if (paletteSize < 8)
            {
                throw new ArgumentException("Palette size must be at least 8.");
            }
            if (paletteSize > 256)
            {
                throw new ArgumentException("Palette size must be at most 256.");
            }

            // reduce the mask length until we have the right number of colors
            while (true)
            {
                // count the number of colors, maybe there are only paletteSize colors?!
                bool tooManyColors = false;
                for (int x = 0; x < img.Width; x++)
                {
                    for (int y = 0; y < img.Height; y++)
                    {
                        if (palette.map.Count >= 255)
                        {
                            tooManyColors = true;
                            break;
                        }
                        palette.GetPaletteColor(img.GetPixel(x, y));
                    }
                    if (palette.map.Count > paletteSize)
                    {
                        break;
                    }
                }

                // check for a good palette
                if (!tooManyColors && palette.map.Count > 0)
                {
                    lastGoodPalette = palette;
                    palette         = new Palette(palette);
                    if (!palette.IncreaseSpetrum())
                    {
                        break;
                    }
                }
                else
                {
                    // did we already find the best palette?
                    if (lastGoodPalette != null)
                    {
                        break;
                    }

                    // generate smaller masks for the next run
                    palette.ReduceSpectrum();
                }
            }

            return(lastGoodPalette);
        }
 public abstract bool SendColorPalette(Palette palette);