SixelEncoder.cs 6.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202
  1. using Terminal.Gui.Drawing.Quant;
  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. /// Gets or sets the quantizer responsible for building a representative
  10. /// limited color palette for images and for mapping novel colors in
  11. /// images to their closest palette color
  12. /// </summary>
  13. public ColorQuantizer Quantizer { get; set; } = new ();
  14. /// <summary>
  15. /// Encode the given bitmap into sixel encoding
  16. /// </summary>
  17. /// <param name="pixels"></param>
  18. /// <returns></returns>
  19. public string EncodeSixel (Color [,] pixels)
  20. {
  21. const string start = "\u001bP"; // Start sixel sequence
  22. const string defaultRatios = "0;0;0"; // Defaults for aspect ratio and grid size
  23. const string completeStartSequence = "q"; // Signals beginning of sixel image data
  24. const string noScaling = "\"1;1;"; // no scaling factors (1x1);
  25. string fillArea = GetFillArea (pixels);
  26. string pallette = GetColorPalette (pixels );
  27. string pixelData = WriteSixel (pixels);
  28. const string terminator = "\u001b\\"; // End sixel sequence
  29. return start + defaultRatios + completeStartSequence + noScaling + fillArea + pallette + pixelData + terminator;
  30. }
  31. /*
  32. A sixel is a column of 6 pixels - with a width of 1 pixel
  33. Column controlled by one sixel character:
  34. [ ] - Bit 0 (top-most pixel)
  35. [ ] - Bit 1
  36. [ ] - Bit 2
  37. [ ] - Bit 3
  38. [ ] - Bit 4
  39. [ ] - Bit 5 (bottom-most pixel)
  40. */
  41. private string WriteSixel (Color [,] pixels)
  42. {
  43. StringBuilder sb = new StringBuilder ();
  44. int height = pixels.GetLength (1);
  45. int width = pixels.GetLength (0);
  46. int n = 1; // Used for checking when to add the line terminator
  47. // Iterate over each row of the image
  48. for (int y = 0; y < height; y += 6)
  49. {
  50. sb.Append (ProcessBand (pixels, y, Math.Min (6, height - y), width));
  51. // Line separator between bands
  52. if (y + 6 < height) // Only add separator if not the last band
  53. {
  54. sb.Append ("-");
  55. }
  56. }
  57. return sb.ToString ();
  58. }
  59. private string ProcessBand (Color [,] pixels, int startY, int bandHeight, int width)
  60. {
  61. var last = new sbyte [Quantizer.Palette.Count + 1];
  62. var code = new byte [Quantizer.Palette.Count + 1];
  63. var accu = new ushort [Quantizer.Palette.Count + 1];
  64. var slots = new short [Quantizer.Palette.Count + 1];
  65. Array.Fill (last, (sbyte)-1);
  66. Array.Fill (accu, (ushort)1);
  67. Array.Fill (slots, (short)-1);
  68. var usedColorIdx = new List<int> ();
  69. var targets = new List<List<string>> ();
  70. // Process columns within the band
  71. for (int x = 0; x < width; ++x)
  72. {
  73. Array.Clear (code, 0, usedColorIdx.Count);
  74. // Process each row in the 6-pixel high band
  75. for (int row = 0; row < bandHeight; ++row)
  76. {
  77. var color = pixels [x, startY + row];
  78. int colorIndex = Quantizer.GetNearestColor (color);
  79. if (slots [colorIndex] == -1)
  80. {
  81. targets.Add (new List<string> ());
  82. if (x > 0)
  83. {
  84. last [usedColorIdx.Count] = 0;
  85. accu [usedColorIdx.Count] = (ushort)x;
  86. }
  87. slots [colorIndex] = (short)usedColorIdx.Count;
  88. usedColorIdx.Add (colorIndex);
  89. }
  90. code [slots [colorIndex]] |= (byte)(1 << row); // Accumulate SIXEL data
  91. }
  92. // Handle transitions between columns
  93. for (int j = 0; j < usedColorIdx.Count; ++j)
  94. {
  95. if (code [j] == last [j])
  96. {
  97. accu [j]++;
  98. }
  99. else
  100. {
  101. if (last [j] != -1)
  102. {
  103. targets [j].Add (CodeToSixel (last [j], accu [j]));
  104. }
  105. last [j] = (sbyte)code [j];
  106. accu [j] = 1;
  107. }
  108. }
  109. }
  110. // Process remaining data for this band
  111. for (int j = 0; j < usedColorIdx.Count; ++j)
  112. {
  113. if (last [j] != 0)
  114. {
  115. targets [j].Add (CodeToSixel (last [j], accu [j]));
  116. }
  117. }
  118. // Build the final output for this band
  119. var result = new StringBuilder ();
  120. for (int j = 0; j < usedColorIdx.Count; ++j)
  121. {
  122. result.Append ($"#{usedColorIdx [j]}{string.Join ("", targets [j])}$");
  123. }
  124. return result.ToString ();
  125. }
  126. private static string CodeToSixel (int code, int repeat)
  127. {
  128. char c = (char)(code + 63);
  129. if (repeat > 3) return "!" + repeat + c;
  130. if (repeat == 3) return c.ToString () + c + c;
  131. if (repeat == 2) return c.ToString () + c;
  132. return c.ToString ();
  133. }
  134. private string GetColorPalette (Color [,] pixels)
  135. {
  136. Quantizer.BuildPalette (pixels);
  137. StringBuilder paletteSb = new StringBuilder ();
  138. for (int i = 0; i < Quantizer.Palette.Count; i++)
  139. {
  140. var color = Quantizer.Palette.ElementAt (i);
  141. paletteSb.AppendFormat ("#{0};2;{1};{2};{3}",
  142. i,
  143. color.R * 100 / 255,
  144. color.G * 100 / 255,
  145. color.B * 100 / 255);
  146. }
  147. return paletteSb.ToString ();
  148. }
  149. private string GetFillArea (Color [,] pixels)
  150. {
  151. int widthInChars = GetWidthInChars (pixels);
  152. int heightInChars = GetHeightInChars (pixels);
  153. return $"{widthInChars};{heightInChars}";
  154. }
  155. private int GetHeightInChars (Color [,] pixels)
  156. {
  157. int height = pixels.GetLength (1);
  158. return (height + 5) / 6;
  159. }
  160. private int GetWidthInChars (Color [,] pixels)
  161. {
  162. return pixels.GetLength (0);
  163. }
  164. }