SixelEncoder.cs 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. using System.Reflection.Metadata;
  2. namespace Terminal.Gui;
  3. /// <summary>
  4. /// Encodes a images into the sixel console image output format.
  5. /// </summary>
  6. public class SixelEncoder
  7. {
  8. /// <summary>
  9. /// Encode the given bitmap into sixel encoding
  10. /// </summary>
  11. /// <param name="pixels"></param>
  12. /// <returns></returns>
  13. public string EncodeSixel (Color [,] pixels)
  14. {
  15. const string start = "\u001bP"; // Start sixel sequence
  16. const string defaultRatios = "0;0;0"; // Defaults for aspect ratio and grid size
  17. const string completeStartSequence = "q"; // Signals beginning of sixel image data
  18. const string noScaling = "\"1;1;"; // no scaling factors (1x1);
  19. string fillArea = GetFillArea (pixels);
  20. string pallette = GetColorPallette (pixels, out var dictionary);
  21. const string pixelData =
  22. "~~~~$-"
  23. + // First 6 rows of red pixels
  24. "~~~~$-"; // Next 6 rows of red pixels
  25. const string terminator = "\u001b\\"; // End sixel sequence
  26. return start + defaultRatios + completeStartSequence + noScaling + fillArea + pallette + pixelData + terminator;
  27. }
  28. private string GetColorPallette (Color [,] pixels, out ColorQuantizer quantizer)
  29. {
  30. quantizer = new ColorQuantizer ();
  31. quantizer.BuildColorPalette (pixels);
  32. // Color definitions in the format "#<index>;<type>;<R>;<G>;<B>" - For type the 2 means RGB. The values range 0 to 100
  33. StringBuilder paletteSb = new StringBuilder ();
  34. for (int i = 0; i < quantizer.Palette.Count; i++)
  35. {
  36. var color = quantizer.Palette [i];
  37. paletteSb.AppendFormat ("#{0};2;{1};{2};{3}",
  38. i,
  39. color.R * 100 / 255,
  40. color.G * 100 / 255,
  41. color.B * 100 / 255);
  42. }
  43. return paletteSb.ToString ();
  44. }
  45. private string GetFillArea (Color [,] pixels)
  46. {
  47. int widthInChars = GetWidthInChars (pixels);
  48. int heightInChars = GetHeightInChars (pixels);
  49. return $"{widthInChars};{heightInChars}";
  50. }
  51. private int GetHeightInChars (Color [,] pixels)
  52. {
  53. // TODO
  54. return 2;
  55. }
  56. private int GetWidthInChars (Color [,] pixels)
  57. {
  58. return 3;
  59. }
  60. }