ImageMagickEncoder.cs 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324
  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.Model.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 Func<IHttpClient> _httpClientFactory;
  19. private readonly IFileSystem _fileSystem;
  20. public ImageMagickEncoder(ILogger logger, IApplicationPaths appPaths, Func<IHttpClient> httpClientFactory, IFileSystem fileSystem)
  21. {
  22. _logger = logger;
  23. _appPaths = appPaths;
  24. _httpClientFactory = httpClientFactory;
  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. // Remove until supported
  44. //"nef",
  45. "orf",
  46. "pef",
  47. "arw",
  48. "webp",
  49. "gif",
  50. "bmp",
  51. "erf",
  52. "raf",
  53. "rw2",
  54. "nrw"
  55. };
  56. }
  57. }
  58. public ImageFormat[] SupportedOutputFormats
  59. {
  60. get
  61. {
  62. if (_webpAvailable)
  63. {
  64. return new[] { ImageFormat.Webp, ImageFormat.Gif, ImageFormat.Jpg, ImageFormat.Png };
  65. }
  66. return new[] { ImageFormat.Gif, ImageFormat.Jpg, ImageFormat.Png };
  67. }
  68. }
  69. private void LogVersion()
  70. {
  71. _logger.Info("ImageMagick version: " + GetVersion());
  72. TestWebp();
  73. Wand.SetMagickThreadCount(1);
  74. }
  75. public static string GetVersion()
  76. {
  77. return Wand.VersionString;
  78. }
  79. private bool _webpAvailable = true;
  80. private void TestWebp()
  81. {
  82. try
  83. {
  84. var tmpPath = Path.Combine(_appPaths.TempDirectory, Guid.NewGuid() + ".webp");
  85. _fileSystem.CreateDirectory(_fileSystem.GetDirectoryName(tmpPath));
  86. using (var wand = new MagickWand(1, 1, new PixelWand("none", 1)))
  87. {
  88. wand.SaveImage(tmpPath);
  89. }
  90. }
  91. catch
  92. {
  93. //_logger.ErrorException("Error loading webp: ", ex);
  94. _webpAvailable = false;
  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, bool autoOrient, int width, int height, int quality, ImageProcessingOptions options, ImageFormat selectedOutputFormat)
  118. {
  119. // Even if the caller specified 100, don't use it because it takes forever
  120. quality = Math.Min(quality, 99);
  121. if (string.IsNullOrWhiteSpace(options.BackgroundColor) || !HasTransparency(inputPath))
  122. {
  123. using (var originalImage = new MagickWand(inputPath))
  124. {
  125. if (options.CropWhiteSpace)
  126. {
  127. originalImage.CurrentImage.TrimImage(10);
  128. }
  129. ScaleImage(originalImage, width, height, options.Blur ?? 0);
  130. if (autoOrient)
  131. {
  132. AutoOrientImage(originalImage);
  133. }
  134. AddForegroundLayer(originalImage, options);
  135. DrawIndicator(originalImage, width, height, options);
  136. originalImage.CurrentImage.CompressionQuality = quality;
  137. originalImage.CurrentImage.StripImage();
  138. originalImage.SaveImage(outputPath);
  139. }
  140. }
  141. else
  142. {
  143. using (var wand = new MagickWand(width, height, options.BackgroundColor))
  144. {
  145. using (var originalImage = new MagickWand(inputPath))
  146. {
  147. ScaleImage(originalImage, width, height, options.Blur ?? 0);
  148. if (autoOrient)
  149. {
  150. AutoOrientImage(originalImage);
  151. }
  152. wand.CurrentImage.CompositeImage(originalImage, CompositeOperator.OverCompositeOp, 0, 0);
  153. AddForegroundLayer(wand, options);
  154. DrawIndicator(wand, width, height, options);
  155. wand.CurrentImage.CompressionQuality = quality;
  156. wand.CurrentImage.StripImage();
  157. wand.SaveImage(outputPath);
  158. }
  159. }
  160. }
  161. }
  162. private void AddForegroundLayer(MagickWand wand, ImageProcessingOptions options)
  163. {
  164. if (string.IsNullOrWhiteSpace(options.ForegroundLayer))
  165. {
  166. return;
  167. }
  168. Double opacity;
  169. if (!Double.TryParse(options.ForegroundLayer, out opacity)) opacity = .4;
  170. using (var pixel = new PixelWand("#000", opacity))
  171. using (var overlay = new MagickWand(wand.CurrentImage.Width, wand.CurrentImage.Height, pixel))
  172. {
  173. wand.CurrentImage.CompositeImage(overlay, CompositeOperator.OverCompositeOp, 0, 0);
  174. }
  175. }
  176. private void AutoOrientImage(MagickWand wand)
  177. {
  178. wand.CurrentImage.AutoOrientImage();
  179. }
  180. public static void RotateImage(MagickWand wand, float angle)
  181. {
  182. using (var pixelWand = new PixelWand("none", 1))
  183. {
  184. wand.CurrentImage.RotateImage(pixelWand, angle);
  185. }
  186. }
  187. private void ScaleImage(MagickWand wand, int width, int height, int blur)
  188. {
  189. var useResize = blur > 1;
  190. if (useResize)
  191. {
  192. wand.CurrentImage.ResizeImage(width, height, FilterTypes.GaussianFilter, blur);
  193. }
  194. else
  195. {
  196. wand.CurrentImage.ScaleImage(width, height);
  197. }
  198. }
  199. /// <summary>
  200. /// Draws the indicator.
  201. /// </summary>
  202. /// <param name="wand">The wand.</param>
  203. /// <param name="imageWidth">Width of the image.</param>
  204. /// <param name="imageHeight">Height of the image.</param>
  205. /// <param name="options">The options.</param>
  206. private void DrawIndicator(MagickWand wand, int imageWidth, int imageHeight, ImageProcessingOptions options)
  207. {
  208. if (!options.AddPlayedIndicator && !options.UnplayedCount.HasValue && options.PercentPlayed.Equals(0))
  209. {
  210. return;
  211. }
  212. try
  213. {
  214. if (options.AddPlayedIndicator)
  215. {
  216. var currentImageSize = new ImageSize(imageWidth, imageHeight);
  217. var task = new PlayedIndicatorDrawer(_appPaths, _httpClientFactory(), _fileSystem).DrawPlayedIndicator(wand, currentImageSize);
  218. Task.WaitAll(task);
  219. }
  220. else if (options.UnplayedCount.HasValue)
  221. {
  222. var currentImageSize = new ImageSize(imageWidth, imageHeight);
  223. new UnplayedCountIndicator(_appPaths, _fileSystem).DrawUnplayedCountIndicator(wand, currentImageSize, options.UnplayedCount.Value);
  224. }
  225. if (options.PercentPlayed > 0)
  226. {
  227. new PercentPlayedDrawer().Process(wand, options.PercentPlayed);
  228. }
  229. }
  230. catch (Exception ex)
  231. {
  232. _logger.ErrorException("Error drawing indicator overlay", ex);
  233. }
  234. }
  235. public void CreateImageCollage(ImageCollageOptions options)
  236. {
  237. double ratio = options.Width;
  238. ratio /= options.Height;
  239. if (ratio >= 1.4)
  240. {
  241. new StripCollageBuilder(_appPaths, _fileSystem).BuildThumbCollage(options.InputPaths.ToList(), options.OutputPath, options.Width, options.Height);
  242. }
  243. else if (ratio >= .9)
  244. {
  245. new StripCollageBuilder(_appPaths, _fileSystem).BuildSquareCollage(options.InputPaths.ToList(), options.OutputPath, options.Width, options.Height);
  246. }
  247. else
  248. {
  249. new StripCollageBuilder(_appPaths, _fileSystem).BuildPosterCollage(options.InputPaths.ToList(), options.OutputPath, options.Width, options.Height);
  250. }
  251. }
  252. public string Name
  253. {
  254. get { return "ImageMagick"; }
  255. }
  256. private bool _disposed;
  257. public void Dispose()
  258. {
  259. _disposed = true;
  260. Wand.CloseEnvironment();
  261. }
  262. private void CheckDisposed()
  263. {
  264. if (_disposed)
  265. {
  266. throw new ObjectDisposedException(GetType().Name);
  267. }
  268. }
  269. public bool SupportsImageCollageCreation
  270. {
  271. get { return true; }
  272. }
  273. public bool SupportsImageEncoding
  274. {
  275. get { return true; }
  276. }
  277. }
  278. }