ImageMagickEncoder.cs 7.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244
  1. using System.Threading.Tasks;
  2. using ImageMagickSharp;
  3. using MediaBrowser.Common.Configuration;
  4. using MediaBrowser.Common.Net;
  5. using MediaBrowser.Controller.Drawing;
  6. using MediaBrowser.Model.Drawing;
  7. using MediaBrowser.Model.Logging;
  8. using System;
  9. using System.IO;
  10. using System.Linq;
  11. namespace Emby.Drawing.ImageMagick
  12. {
  13. public class ImageMagickEncoder : IImageEncoder
  14. {
  15. private readonly ILogger _logger;
  16. private readonly IApplicationPaths _appPaths;
  17. private readonly IHttpClient _httpClient;
  18. public ImageMagickEncoder(ILogger logger, IApplicationPaths appPaths, IHttpClient httpClient)
  19. {
  20. _logger = logger;
  21. _appPaths = appPaths;
  22. _httpClient = httpClient;
  23. LogImageMagickVersion();
  24. }
  25. public string[] SupportedInputFormats
  26. {
  27. get
  28. {
  29. // Some common file name extensions for RAW picture files include: .cr2, .crw, .dng, .nef, .orf, .rw2, .pef, .arw, .sr2, .srf, and .tif.
  30. return new[]
  31. {
  32. "tiff",
  33. "jpeg",
  34. "jpg",
  35. "png",
  36. "aiff",
  37. "cr2",
  38. "crw",
  39. "dng",
  40. "nef",
  41. "orf",
  42. "pef",
  43. "arw",
  44. "webp",
  45. "gif",
  46. "bmp"
  47. };
  48. }
  49. }
  50. public ImageFormat[] SupportedOutputFormats
  51. {
  52. get
  53. {
  54. if (_webpAvailable)
  55. {
  56. return new[] { ImageFormat.Webp, ImageFormat.Gif, ImageFormat.Jpg, ImageFormat.Png };
  57. }
  58. return new[] { ImageFormat.Gif, ImageFormat.Jpg, ImageFormat.Png };
  59. }
  60. }
  61. private void LogImageMagickVersion()
  62. {
  63. _logger.Info("ImageMagick version: " + Wand.VersionString);
  64. TestWebp();
  65. Wand.SetMagickThreadCount(1);
  66. }
  67. private bool _webpAvailable = true;
  68. private void TestWebp()
  69. {
  70. try
  71. {
  72. var tmpPath = Path.Combine(_appPaths.TempDirectory, Guid.NewGuid() + ".webp");
  73. Directory.CreateDirectory(Path.GetDirectoryName(tmpPath));
  74. using (var wand = new MagickWand(1, 1, new PixelWand("none", 1)))
  75. {
  76. wand.SaveImage(tmpPath);
  77. }
  78. }
  79. catch (Exception ex)
  80. {
  81. _logger.ErrorException("Error loading webp: ", ex);
  82. _webpAvailable = false;
  83. }
  84. }
  85. public void CropWhiteSpace(string inputPath, string outputPath)
  86. {
  87. CheckDisposed();
  88. using (var wand = new MagickWand(inputPath))
  89. {
  90. wand.CurrentImage.TrimImage(10);
  91. wand.SaveImage(outputPath);
  92. }
  93. }
  94. public ImageSize GetImageSize(string path)
  95. {
  96. CheckDisposed();
  97. using (var wand = new MagickWand())
  98. {
  99. wand.PingImage(path);
  100. var img = wand.CurrentImage;
  101. return new ImageSize
  102. {
  103. Width = img.Width,
  104. Height = img.Height
  105. };
  106. }
  107. }
  108. private bool HasTransparency(string path)
  109. {
  110. var ext = Path.GetExtension(path);
  111. return string.Equals(ext, ".png", StringComparison.OrdinalIgnoreCase) ||
  112. string.Equals(ext, ".webp", StringComparison.OrdinalIgnoreCase);
  113. }
  114. public void EncodeImage(string inputPath, string outputPath, int width, int height, int quality, ImageProcessingOptions options)
  115. {
  116. if (string.IsNullOrWhiteSpace(options.BackgroundColor) || !HasTransparency(inputPath))
  117. {
  118. using (var originalImage = new MagickWand(inputPath))
  119. {
  120. originalImage.CurrentImage.ResizeImage(width, height);
  121. DrawIndicator(originalImage, width, height, options);
  122. originalImage.CurrentImage.CompressionQuality = quality;
  123. originalImage.SaveImage(outputPath);
  124. }
  125. }
  126. else
  127. {
  128. using (var wand = new MagickWand(width, height, options.BackgroundColor))
  129. {
  130. using (var originalImage = new MagickWand(inputPath))
  131. {
  132. originalImage.CurrentImage.ResizeImage(width, height);
  133. wand.CurrentImage.CompositeImage(originalImage, CompositeOperator.OverCompositeOp, 0, 0);
  134. DrawIndicator(wand, width, height, options);
  135. wand.CurrentImage.CompressionQuality = quality;
  136. wand.SaveImage(outputPath);
  137. }
  138. }
  139. }
  140. }
  141. /// <summary>
  142. /// Draws the indicator.
  143. /// </summary>
  144. /// <param name="wand">The wand.</param>
  145. /// <param name="imageWidth">Width of the image.</param>
  146. /// <param name="imageHeight">Height of the image.</param>
  147. /// <param name="options">The options.</param>
  148. private void DrawIndicator(MagickWand wand, int imageWidth, int imageHeight, ImageProcessingOptions options)
  149. {
  150. if (!options.AddPlayedIndicator && !options.UnplayedCount.HasValue && options.PercentPlayed.Equals(0))
  151. {
  152. return;
  153. }
  154. try
  155. {
  156. if (options.AddPlayedIndicator)
  157. {
  158. var currentImageSize = new ImageSize(imageWidth, imageHeight);
  159. var task = new PlayedIndicatorDrawer(_appPaths, _httpClient).DrawPlayedIndicator(wand, currentImageSize);
  160. Task.WaitAll(task);
  161. }
  162. else if (options.UnplayedCount.HasValue)
  163. {
  164. var currentImageSize = new ImageSize(imageWidth, imageHeight);
  165. new UnplayedCountIndicator(_appPaths).DrawUnplayedCountIndicator(wand, currentImageSize, options.UnplayedCount.Value);
  166. }
  167. if (options.PercentPlayed > 0)
  168. {
  169. new PercentPlayedDrawer().Process(wand, options.PercentPlayed);
  170. }
  171. }
  172. catch (Exception ex)
  173. {
  174. _logger.ErrorException("Error drawing indicator overlay", ex);
  175. }
  176. }
  177. public void CreateImageCollage(ImageCollageOptions options)
  178. {
  179. double ratio = options.Width;
  180. ratio /= options.Height;
  181. if (ratio >= 1.4)
  182. {
  183. new StripCollageBuilder(_appPaths).BuildThumbCollage(options.InputPaths.ToList(), options.OutputPath, options.Width, options.Height, options.Text);
  184. }
  185. else if (ratio >= .9)
  186. {
  187. new StripCollageBuilder(_appPaths).BuildSquareCollage(options.InputPaths.ToList(), options.OutputPath, options.Width, options.Height, options.Text);
  188. }
  189. else
  190. {
  191. new StripCollageBuilder(_appPaths).BuildPosterCollage(options.InputPaths.ToList(), options.OutputPath, options.Width, options.Height, options.Text);
  192. }
  193. }
  194. public string Name
  195. {
  196. get { return "ImageMagick"; }
  197. }
  198. private bool _disposed;
  199. public void Dispose()
  200. {
  201. _disposed = true;
  202. Wand.CloseEnvironment();
  203. }
  204. private void CheckDisposed()
  205. {
  206. if (_disposed)
  207. {
  208. throw new ObjectDisposedException(GetType().Name);
  209. }
  210. }
  211. }
  212. }