ImageMagickEncoder.cs 8.0 KB

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