StripCollageBuilder.cs 7.8 KB

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