SixelEncoder.cs 6.2 KB

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