/// <summary>Detects the most common colors.</summary> /// <param name="max">The maximum number of colors to retrieve.</param> /// <returns>Returns an array of <see cref="T:Cave.Media.ARGB" /> values.</returns> public IList <ARGB> DetectColors(int max) { if ((Width + Height) / 2 > max) { using (var bmp = Resize(max, max, ResizeMode.None)) { return(bmp.DetectColors(max)); } } var colorCounters = new List <ColorCounter>(); for (int y = 0; y < Height; y++) { var data = Data.Data; var colorDict = new Dictionary <ARGB, ColorCounter>(); unsafe { fixed(int *p = &data[0]) { for (int i = 0; i < data.Length; i++) { ARGB color = p[i]; if (!colorDict.ContainsKey(color)) { colorDict.Add(color, new ColorCounter(color, 1)); } else { colorDict[color].Count++; } } } } colorCounters.AddRange(colorDict.Values); } uint distance = 255; while (colorCounters.Count > max) { colorCounters.Sort(); colorCounters = ColorCounter.Reduce(colorCounters, ref distance); distance += 255; } colorCounters.Sort(); var colors = new List <ARGB>(colorCounters.Count); for (int i = 0; i < colorCounters.Count; i++) { colors.Add(colorCounters[i].Color); } return(colors); }
/// <summary> /// Reduces the the colors of the image to the specified color count. /// </summary> /// <param name="colorCount">Number of colors to keep.</param> /// <returns>Returns the resulting color palette.</returns> public ARGB[] GetColors(uint colorCount) { var colorCounters = new List <ColorCounter>(); { var colorDict = new Dictionary <int, ColorCounter>(); for (var i = 0; i < Data.Length; i++) { var color = Data[i]; if (!colorDict.ContainsKey(color)) { colorDict.Add(color, new ColorCounter(color, 1)); } else { colorDict[color].Count++; } } colorCounters.AddRange(colorDict.Values); } var distance = 255000 / colorCount; while (colorCounters.Count > colorCount) { colorCounters.Sort(); colorCounters = ColorCounter.Reduce(colorCounters, ref distance); distance *= 2; } colorCounters.Sort(); var colors = new ARGB[colorCounters.Count]; for (var i = 0; i < colors.Length; i++) { colors[i] = colorCounters[i].Color; } return(colors); }