StripCollageBuilder.cs 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217
  1. using System;
  2. using System.Collections.Generic;
  3. using System.IO;
  4. using System.Text.RegularExpressions;
  5. using SkiaSharp;
  6. namespace Jellyfin.Drawing.Skia
  7. {
  8. /// <summary>
  9. /// Used to build collages of multiple images arranged in vertical strips.
  10. /// </summary>
  11. public class StripCollageBuilder
  12. {
  13. private readonly SkiaEncoder _skiaEncoder;
  14. /// <summary>
  15. /// Initializes a new instance of the <see cref="StripCollageBuilder"/> class.
  16. /// </summary>
  17. /// <param name="skiaEncoder">The encoder to use for building collages.</param>
  18. public StripCollageBuilder(SkiaEncoder skiaEncoder)
  19. {
  20. _skiaEncoder = skiaEncoder;
  21. }
  22. /// <summary>
  23. /// Check which format an image has been encoded with using its filename extension.
  24. /// </summary>
  25. /// <param name="outputPath">The path to the image to get the format for.</param>
  26. /// <returns>The image format.</returns>
  27. public static SKEncodedImageFormat GetEncodedFormat(string outputPath)
  28. {
  29. if (outputPath == null)
  30. {
  31. throw new ArgumentNullException(nameof(outputPath));
  32. }
  33. var ext = Path.GetExtension(outputPath);
  34. if (string.Equals(ext, ".jpg", StringComparison.OrdinalIgnoreCase)
  35. || string.Equals(ext, ".jpeg", StringComparison.OrdinalIgnoreCase))
  36. {
  37. return SKEncodedImageFormat.Jpeg;
  38. }
  39. if (string.Equals(ext, ".webp", StringComparison.OrdinalIgnoreCase))
  40. {
  41. return SKEncodedImageFormat.Webp;
  42. }
  43. if (string.Equals(ext, ".gif", StringComparison.OrdinalIgnoreCase))
  44. {
  45. return SKEncodedImageFormat.Gif;
  46. }
  47. if (string.Equals(ext, ".bmp", StringComparison.OrdinalIgnoreCase))
  48. {
  49. return SKEncodedImageFormat.Bmp;
  50. }
  51. // default to png
  52. return SKEncodedImageFormat.Png;
  53. }
  54. /// <summary>
  55. /// Create a square collage.
  56. /// </summary>
  57. /// <param name="paths">The paths of the images to use in the collage.</param>
  58. /// <param name="outputPath">The path at which to place the resulting collage image.</param>
  59. /// <param name="width">The desired width of the collage.</param>
  60. /// <param name="height">The desired height of the collage.</param>
  61. public void BuildSquareCollage(IReadOnlyList<string> paths, string outputPath, int width, int height)
  62. {
  63. using var bitmap = BuildSquareCollageBitmap(paths, width, height);
  64. using var outputStream = new SKFileWStream(outputPath);
  65. using var pixmap = new SKPixmap(new SKImageInfo(width, height), bitmap.GetPixels());
  66. pixmap.Encode(outputStream, GetEncodedFormat(outputPath), 90);
  67. }
  68. /// <summary>
  69. /// Create a thumb collage.
  70. /// </summary>
  71. /// <param name="paths">The paths of the images to use in the collage.</param>
  72. /// <param name="outputPath">The path at which to place the resulting image.</param>
  73. /// <param name="width">The desired width of the collage.</param>
  74. /// <param name="height">The desired height of the collage.</param>
  75. /// <param name="libraryName">The name of the library to draw on the collage.</param>
  76. public void BuildThumbCollage(IReadOnlyList<string> paths, string outputPath, int width, int height, string? libraryName)
  77. {
  78. using var bitmap = BuildThumbCollageBitmap(paths, width, height, libraryName);
  79. using var outputStream = new SKFileWStream(outputPath);
  80. using var pixmap = new SKPixmap(new SKImageInfo(width, height), bitmap.GetPixels());
  81. pixmap.Encode(outputStream, GetEncodedFormat(outputPath), 90);
  82. }
  83. private SKBitmap BuildThumbCollageBitmap(IReadOnlyList<string> paths, int width, int height, string? libraryName)
  84. {
  85. var bitmap = new SKBitmap(width, height);
  86. using var canvas = new SKCanvas(bitmap);
  87. canvas.Clear(SKColors.Black);
  88. using var backdrop = GetNextValidImage(paths, 0, out _);
  89. if (backdrop == null)
  90. {
  91. return bitmap;
  92. }
  93. // resize to the same aspect as the original
  94. var backdropHeight = Math.Abs(width * backdrop.Height / backdrop.Width);
  95. using var residedBackdrop = SkiaEncoder.ResizeImage(backdrop, new SKImageInfo(width, backdropHeight, backdrop.ColorType, backdrop.AlphaType, backdrop.ColorSpace));
  96. // draw the backdrop
  97. canvas.DrawImage(residedBackdrop, 0, 0);
  98. // draw shadow rectangle
  99. var paintColor = new SKPaint
  100. {
  101. Color = SKColors.Black.WithAlpha(0x78),
  102. Style = SKPaintStyle.Fill
  103. };
  104. canvas.DrawRect(0, 0, width, height, paintColor);
  105. var typeFace = SKTypeface.FromFamilyName("sans-serif", SKFontStyleWeight.Bold, SKFontStyleWidth.Normal, SKFontStyleSlant.Upright);
  106. // use the system fallback to find a typeface for the given CJK character
  107. var nonCjkPattern = @"[^\p{IsCJKUnifiedIdeographs}\p{IsCJKUnifiedIdeographsExtensionA}\p{IsKatakana}\p{IsHiragana}\p{IsHangulSyllables}\p{IsHangulJamo}]";
  108. var filteredName = Regex.Replace(libraryName ?? string.Empty, nonCjkPattern, string.Empty);
  109. if (!string.IsNullOrEmpty(filteredName))
  110. {
  111. typeFace = SKFontManager.Default.MatchCharacter(null, SKFontStyleWeight.Bold, SKFontStyleWidth.Normal, SKFontStyleSlant.Upright, null, filteredName[0]);
  112. }
  113. // draw library name
  114. var textPaint = new SKPaint
  115. {
  116. Color = SKColors.White,
  117. Style = SKPaintStyle.Fill,
  118. TextSize = 112,
  119. TextAlign = SKTextAlign.Center,
  120. Typeface = typeFace,
  121. IsAntialias = true
  122. };
  123. // scale down text to 90% of the width if text is larger than 95% of the width
  124. var textWidth = textPaint.MeasureText(libraryName);
  125. if (textWidth > width * 0.95)
  126. {
  127. textPaint.TextSize = 0.9f * width * textPaint.TextSize / textWidth;
  128. }
  129. canvas.DrawText(libraryName, width / 2f, (height / 2f) + (textPaint.FontMetrics.XHeight / 2), textPaint);
  130. return bitmap;
  131. }
  132. private SKBitmap? GetNextValidImage(IReadOnlyList<string> paths, int currentIndex, out int newIndex)
  133. {
  134. var imagesTested = new Dictionary<int, int>();
  135. SKBitmap? bitmap = null;
  136. while (imagesTested.Count < paths.Count)
  137. {
  138. if (currentIndex >= paths.Count)
  139. {
  140. currentIndex = 0;
  141. }
  142. bitmap = _skiaEncoder.Decode(paths[currentIndex], false, null, out _);
  143. imagesTested[currentIndex] = 0;
  144. currentIndex++;
  145. if (bitmap != null)
  146. {
  147. break;
  148. }
  149. }
  150. newIndex = currentIndex;
  151. return bitmap;
  152. }
  153. private SKBitmap BuildSquareCollageBitmap(IReadOnlyList<string> paths, int width, int height)
  154. {
  155. var bitmap = new SKBitmap(width, height);
  156. var imageIndex = 0;
  157. var cellWidth = width / 2;
  158. var cellHeight = height / 2;
  159. using var canvas = new SKCanvas(bitmap);
  160. for (var x = 0; x < 2; x++)
  161. {
  162. for (var y = 0; y < 2; y++)
  163. {
  164. using var currentBitmap = GetNextValidImage(paths, imageIndex, out int newIndex);
  165. imageIndex = newIndex;
  166. if (currentBitmap == null)
  167. {
  168. continue;
  169. }
  170. // Scale image. The FromBitmap creates a copy
  171. var imageInfo = new SKImageInfo(cellWidth, cellHeight, currentBitmap.ColorType, currentBitmap.AlphaType, currentBitmap.ColorSpace);
  172. using var resizedBitmap = SKBitmap.FromImage(SkiaEncoder.ResizeImage(currentBitmap, imageInfo));
  173. // draw this image into the strip at the next position
  174. var xPos = x * cellWidth;
  175. var yPos = y * cellHeight;
  176. canvas.DrawBitmap(resizedBitmap, xPos, yPos);
  177. }
  178. }
  179. return bitmap;
  180. }
  181. }
  182. }