ImageMagickEncoder.cs 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268
  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. 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. LogVersion();
  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 LogVersion()
  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
  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. SaveDelay();
  97. }
  98. public ImageSize GetImageSize(string path)
  99. {
  100. CheckDisposed();
  101. using (var wand = new MagickWand())
  102. {
  103. wand.PingImage(path);
  104. var img = wand.CurrentImage;
  105. return new ImageSize
  106. {
  107. Width = img.Width,
  108. Height = img.Height
  109. };
  110. }
  111. }
  112. private bool HasTransparency(string path)
  113. {
  114. var ext = Path.GetExtension(path);
  115. return string.Equals(ext, ".png", StringComparison.OrdinalIgnoreCase) ||
  116. string.Equals(ext, ".webp", StringComparison.OrdinalIgnoreCase);
  117. }
  118. public void EncodeImage(string inputPath, string outputPath, int width, int height, int quality, ImageProcessingOptions options)
  119. {
  120. if (string.IsNullOrWhiteSpace(options.BackgroundColor) || !HasTransparency(inputPath))
  121. {
  122. using (var originalImage = new MagickWand(inputPath))
  123. {
  124. originalImage.CurrentImage.ResizeImage(width, height);
  125. DrawIndicator(originalImage, width, height, options);
  126. originalImage.CurrentImage.CompressionQuality = quality;
  127. originalImage.SaveImage(outputPath);
  128. }
  129. }
  130. else
  131. {
  132. using (var wand = new MagickWand(width, height, options.BackgroundColor))
  133. {
  134. using (var originalImage = new MagickWand(inputPath))
  135. {
  136. originalImage.CurrentImage.ResizeImage(width, height);
  137. wand.CurrentImage.CompositeImage(originalImage, CompositeOperator.OverCompositeOp, 0, 0);
  138. DrawIndicator(wand, width, height, options);
  139. wand.CurrentImage.CompressionQuality = quality;
  140. wand.SaveImage(outputPath);
  141. }
  142. }
  143. }
  144. SaveDelay();
  145. }
  146. /// <summary>
  147. /// Draws the indicator.
  148. /// </summary>
  149. /// <param name="wand">The wand.</param>
  150. /// <param name="imageWidth">Width of the image.</param>
  151. /// <param name="imageHeight">Height of the image.</param>
  152. /// <param name="options">The options.</param>
  153. private void DrawIndicator(MagickWand wand, int imageWidth, int imageHeight, ImageProcessingOptions options)
  154. {
  155. if (!options.AddPlayedIndicator && !options.UnplayedCount.HasValue && options.PercentPlayed.Equals(0))
  156. {
  157. return;
  158. }
  159. try
  160. {
  161. if (options.AddPlayedIndicator)
  162. {
  163. var currentImageSize = new ImageSize(imageWidth, imageHeight);
  164. var task = new PlayedIndicatorDrawer(_appPaths, _httpClient, _fileSystem).DrawPlayedIndicator(wand, currentImageSize);
  165. Task.WaitAll(task);
  166. }
  167. else if (options.UnplayedCount.HasValue)
  168. {
  169. var currentImageSize = new ImageSize(imageWidth, imageHeight);
  170. new UnplayedCountIndicator(_appPaths, _fileSystem).DrawUnplayedCountIndicator(wand, currentImageSize, options.UnplayedCount.Value);
  171. }
  172. if (options.PercentPlayed > 0)
  173. {
  174. new PercentPlayedDrawer().Process(wand, options.PercentPlayed);
  175. }
  176. }
  177. catch (Exception ex)
  178. {
  179. _logger.ErrorException("Error drawing indicator overlay", ex);
  180. }
  181. }
  182. public void CreateImageCollage(ImageCollageOptions options)
  183. {
  184. double ratio = options.Width;
  185. ratio /= options.Height;
  186. if (ratio >= 1.4)
  187. {
  188. new StripCollageBuilder(_appPaths, _fileSystem).BuildThumbCollage(options.InputPaths.ToList(), options.OutputPath, options.Width, options.Height, options.Text);
  189. }
  190. else if (ratio >= .9)
  191. {
  192. new StripCollageBuilder(_appPaths, _fileSystem).BuildSquareCollage(options.InputPaths.ToList(), options.OutputPath, options.Width, options.Height, options.Text);
  193. }
  194. else
  195. {
  196. new StripCollageBuilder(_appPaths, _fileSystem).BuildPosterCollage(options.InputPaths.ToList(), options.OutputPath, options.Width, options.Height, options.Text);
  197. }
  198. SaveDelay();
  199. }
  200. private void SaveDelay()
  201. {
  202. // For some reason the images are not always getting released right away
  203. var task = Task.Delay(300);
  204. Task.WaitAll(task);
  205. }
  206. public string Name
  207. {
  208. get { return "ImageMagick"; }
  209. }
  210. private bool _disposed;
  211. public void Dispose()
  212. {
  213. _disposed = true;
  214. Wand.CloseEnvironment();
  215. }
  216. private void CheckDisposed()
  217. {
  218. if (_disposed)
  219. {
  220. throw new ObjectDisposedException(GetType().Name);
  221. }
  222. }
  223. public bool SupportsImageCollageCreation
  224. {
  225. get { return true; }
  226. }
  227. public bool SupportsImageEncoding
  228. {
  229. get { return true; }
  230. }
  231. }
  232. }