ColorQuantizer.cs 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. using System.Collections.ObjectModel;
  2. namespace Terminal.Gui.Drawing.Quant;
  3. /// <summary>
  4. /// Translates colors in an image into a Palette of up to 256 colors.
  5. /// </summary>
  6. public class ColorQuantizer
  7. {
  8. /// <summary>
  9. /// Gets the current colors in the palette based on the last call to
  10. /// <see cref="BuildPalette"/>.
  11. /// </summary>
  12. public IReadOnlyCollection<Color> Palette { get; private set; } = new List<Color> ();
  13. /// <summary>
  14. /// Gets or sets the maximum number of colors to put into the <see cref="Palette"/>.
  15. /// Defaults to 256 (the maximum for sixel images).
  16. /// </summary>
  17. public int MaxColors { get; set; } = 256;
  18. /// <summary>
  19. /// Gets or sets the algorithm used to map novel colors into existing
  20. /// palette colors (closest match). Defaults to <see cref="CIE94ColorDistance"/>
  21. /// </summary>
  22. public IColorDistance DistanceAlgorithm { get; set; } = new CIE94ColorDistance ();
  23. /// <summary>
  24. /// Gets or sets the algorithm used to build the <see cref="Palette"/>.
  25. /// Defaults to <see cref="MedianCutPaletteBuilder"/>
  26. /// </summary>
  27. public IPaletteBuilder PaletteBuildingAlgorithm { get; set; } = new MedianCutPaletteBuilder ();
  28. public void BuildPalette (Color [,] pixels)
  29. {
  30. List<Color> allColors = new List<Color> ();
  31. int width = pixels.GetLength (0);
  32. int height = pixels.GetLength (1);
  33. for (int x = 0; x < width; x++)
  34. {
  35. for (int y = 0; y < height; y++)
  36. {
  37. allColors.Add (pixels [x, y]);
  38. }
  39. }
  40. Palette = PaletteBuildingAlgorithm.BuildPalette (allColors, MaxColors);
  41. }
  42. public int GetNearestColor (Color toTranslate)
  43. {
  44. // Simple nearest color matching based on Euclidean distance in RGB space
  45. double minDistance = double.MaxValue;
  46. int nearestIndex = 0;
  47. for (var index = 0; index < Palette.Count; index++)
  48. {
  49. Color color = Palette.ElementAt (index);
  50. double distance = DistanceAlgorithm.CalculateDistance (color, toTranslate);
  51. if (distance < minDistance)
  52. {
  53. minDistance = distance;
  54. nearestIndex = index;
  55. }
  56. }
  57. return nearestIndex;
  58. }
  59. }