StripCollageBuilder.cs 7.5 KB

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