ImageMagickEncoder.cs 8.3 KB

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