SixelEncoder.cs 6.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223
  1. using Terminal.Gui;
  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. Special Characters
  41. The '-' acts like '\n'. It moves the drawing cursor
  42. to beginning of next line
  43. The '$' acts like the <Home> key. It moves drawing
  44. cursor back to beginning of the current line
  45. e.g. to draw more color layers.
  46. */
  47. /**
  48. * This method is adapted from
  49. * https://github.com/jerch/node-sixel/
  50. *
  51. * Copyright (c) 2019 Joerg Breitbart.
  52. * @license MIT
  53. */
  54. private string WriteSixel (Color [,] pixels)
  55. {
  56. StringBuilder sb = new StringBuilder ();
  57. int height = pixels.GetLength (1);
  58. int width = pixels.GetLength (0);
  59. // Iterate over each 'row' of the image. Because each sixel write operation
  60. // outputs a screen area 6 pixels high (and 1+ across) we must process the image
  61. // 6 'y' units at once (1 band)
  62. for (int y = 0; y < height; y += 6)
  63. {
  64. sb.Append (ProcessBand (pixels, y, Math.Min (6, height - y), width));
  65. // Line separator between bands
  66. if (y + 6 < height) // Only add separator if not the last band
  67. {
  68. // This completes the drawing of the current line of sixel and
  69. // returns the 'cursor' to beginning next line, newly drawn sixel
  70. // after this will draw in the next 6 pixel high band (i.e. below).
  71. sb.Append ("-");
  72. }
  73. }
  74. return sb.ToString ();
  75. }
  76. private string ProcessBand (Color [,] pixels, int startY, int bandHeight, int width)
  77. {
  78. var last = new sbyte [Quantizer.Palette.Count + 1];
  79. var code = new byte [Quantizer.Palette.Count + 1];
  80. var accu = new ushort [Quantizer.Palette.Count + 1];
  81. var slots = new short [Quantizer.Palette.Count + 1];
  82. Array.Fill (last, (sbyte)-1);
  83. Array.Fill (accu, (ushort)1);
  84. Array.Fill (slots, (short)-1);
  85. var usedColorIdx = new List<int> ();
  86. var targets = new List<List<string>> ();
  87. // Process columns within the band
  88. for (int x = 0; x < width; ++x)
  89. {
  90. Array.Clear (code, 0, usedColorIdx.Count);
  91. // Process each row in the 6-pixel high band
  92. for (int row = 0; row < bandHeight; ++row)
  93. {
  94. var color = pixels [x, startY + row];
  95. int colorIndex = Quantizer.GetNearestColor (color);
  96. if (slots [colorIndex] == -1)
  97. {
  98. targets.Add (new List<string> ());
  99. if (x > 0)
  100. {
  101. last [usedColorIdx.Count] = 0;
  102. accu [usedColorIdx.Count] = (ushort)x;
  103. }
  104. slots [colorIndex] = (short)usedColorIdx.Count;
  105. usedColorIdx.Add (colorIndex);
  106. }
  107. code [slots [colorIndex]] |= (byte)(1 << row); // Accumulate SIXEL data
  108. }
  109. // Handle transitions between columns
  110. for (int j = 0; j < usedColorIdx.Count; ++j)
  111. {
  112. if (code [j] == last [j])
  113. {
  114. accu [j]++;
  115. }
  116. else
  117. {
  118. if (last [j] != -1)
  119. {
  120. targets [j].Add (CodeToSixel (last [j], accu [j]));
  121. }
  122. last [j] = (sbyte)code [j];
  123. accu [j] = 1;
  124. }
  125. }
  126. }
  127. // Process remaining data for this band
  128. for (int j = 0; j < usedColorIdx.Count; ++j)
  129. {
  130. if (last [j] != 0)
  131. {
  132. targets [j].Add (CodeToSixel (last [j], accu [j]));
  133. }
  134. }
  135. // Build the final output for this band
  136. var result = new StringBuilder ();
  137. for (int j = 0; j < usedColorIdx.Count; ++j)
  138. {
  139. result.Append ($"#{usedColorIdx [j]}{string.Join ("", targets [j])}$");
  140. }
  141. return result.ToString ();
  142. }
  143. private static string CodeToSixel (int code, int repeat)
  144. {
  145. char c = (char)(code + 63);
  146. if (repeat > 3) return "!" + repeat + c;
  147. if (repeat == 3) return c.ToString () + c + c;
  148. if (repeat == 2) return c.ToString () + c;
  149. return c.ToString ();
  150. }
  151. private string GetColorPalette (Color [,] pixels)
  152. {
  153. Quantizer.BuildPalette (pixels);
  154. StringBuilder paletteSb = new StringBuilder ();
  155. for (int i = 0; i < Quantizer.Palette.Count; i++)
  156. {
  157. var color = Quantizer.Palette.ElementAt (i);
  158. paletteSb.AppendFormat ("#{0};2;{1};{2};{3}",
  159. i,
  160. color.R * 100 / 255,
  161. color.G * 100 / 255,
  162. color.B * 100 / 255);
  163. }
  164. return paletteSb.ToString ();
  165. }
  166. private string GetFillArea (Color [,] pixels)
  167. {
  168. int widthInChars = GetWidthInChars (pixels);
  169. int heightInChars = GetHeightInChars (pixels);
  170. return $"{widthInChars};{heightInChars}";
  171. }
  172. private int GetHeightInChars (Color [,] pixels)
  173. {
  174. int height = pixels.GetLength (1);
  175. return (height + 5) / 6;
  176. }
  177. private int GetWidthInChars (Color [,] pixels)
  178. {
  179. return pixels.GetLength (0);
  180. }
  181. }