ImageMagickEncoder.cs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333
  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. using MediaBrowser.Controller.Configuration;
  13. using MediaBrowser.Controller.IO;
  14. using MediaBrowser.Model.IO;
  15. namespace Emby.Drawing.ImageMagick
  16. {
  17. public class ImageMagickEncoder : IImageEncoder
  18. {
  19. private readonly ILogger _logger;
  20. private readonly IApplicationPaths _appPaths;
  21. private readonly IHttpClient _httpClient;
  22. private readonly IFileSystem _fileSystem;
  23. private readonly IServerConfigurationManager _config;
  24. public ImageMagickEncoder(ILogger logger, IApplicationPaths appPaths, IHttpClient httpClient, IFileSystem fileSystem, IServerConfigurationManager config)
  25. {
  26. _logger = logger;
  27. _appPaths = appPaths;
  28. _httpClient = httpClient;
  29. _fileSystem = fileSystem;
  30. _config = config;
  31. LogVersion();
  32. }
  33. public string[] SupportedInputFormats
  34. {
  35. get
  36. {
  37. // Some common file name extensions for RAW picture files include: .cr2, .crw, .dng, .nef, .orf, .rw2, .pef, .arw, .sr2, .srf, and .tif.
  38. return new[]
  39. {
  40. "tiff",
  41. "jpeg",
  42. "jpg",
  43. "png",
  44. "aiff",
  45. "cr2",
  46. "crw",
  47. "dng",
  48. "nef",
  49. "orf",
  50. "pef",
  51. "arw",
  52. "webp",
  53. "gif",
  54. "bmp",
  55. "erf",
  56. "raf",
  57. "rw2",
  58. "nrw"
  59. };
  60. }
  61. }
  62. public ImageFormat[] SupportedOutputFormats
  63. {
  64. get
  65. {
  66. if (_webpAvailable)
  67. {
  68. return new[] { ImageFormat.Webp, ImageFormat.Gif, ImageFormat.Jpg, ImageFormat.Png };
  69. }
  70. return new[] { ImageFormat.Gif, ImageFormat.Jpg, ImageFormat.Png };
  71. }
  72. }
  73. private void LogVersion()
  74. {
  75. _logger.Info("ImageMagick version: " + GetVersion());
  76. TestWebp();
  77. Wand.SetMagickThreadCount(1);
  78. }
  79. public static string GetVersion()
  80. {
  81. return Wand.VersionString;
  82. }
  83. private bool _webpAvailable = true;
  84. private void TestWebp()
  85. {
  86. try
  87. {
  88. var tmpPath = Path.Combine(_appPaths.TempDirectory, Guid.NewGuid() + ".webp");
  89. _fileSystem.CreateDirectory(Path.GetDirectoryName(tmpPath));
  90. using (var wand = new MagickWand(1, 1, new PixelWand("none", 1)))
  91. {
  92. wand.SaveImage(tmpPath);
  93. }
  94. }
  95. catch
  96. {
  97. //_logger.ErrorException("Error loading webp: ", ex);
  98. _webpAvailable = false;
  99. }
  100. }
  101. public void CropWhiteSpace(string inputPath, string outputPath)
  102. {
  103. CheckDisposed();
  104. using (var wand = new MagickWand(inputPath))
  105. {
  106. wand.CurrentImage.TrimImage(10);
  107. wand.SaveImage(outputPath);
  108. }
  109. }
  110. public ImageSize GetImageSize(string path)
  111. {
  112. CheckDisposed();
  113. using (var wand = new MagickWand())
  114. {
  115. wand.PingImage(path);
  116. var img = wand.CurrentImage;
  117. return new ImageSize
  118. {
  119. Width = img.Width,
  120. Height = img.Height
  121. };
  122. }
  123. }
  124. private bool HasTransparency(string path)
  125. {
  126. var ext = Path.GetExtension(path);
  127. return string.Equals(ext, ".png", StringComparison.OrdinalIgnoreCase) ||
  128. string.Equals(ext, ".webp", StringComparison.OrdinalIgnoreCase);
  129. }
  130. public void EncodeImage(string inputPath, string outputPath, bool autoOrient, int width, int height, int quality, ImageProcessingOptions options, ImageFormat selectedOutputFormat)
  131. {
  132. // Even if the caller specified 100, don't use it because it takes forever
  133. quality = Math.Min(quality, 99);
  134. if (string.IsNullOrWhiteSpace(options.BackgroundColor) || !HasTransparency(inputPath))
  135. {
  136. using (var originalImage = new MagickWand(inputPath))
  137. {
  138. ScaleImage(originalImage, width, height);
  139. if (autoOrient)
  140. {
  141. AutoOrientImage(originalImage);
  142. }
  143. AddForegroundLayer(originalImage, options);
  144. DrawIndicator(originalImage, width, height, options);
  145. originalImage.CurrentImage.CompressionQuality = quality;
  146. originalImage.CurrentImage.StripImage();
  147. originalImage.SaveImage(outputPath);
  148. }
  149. }
  150. else
  151. {
  152. using (var wand = new MagickWand(width, height, options.BackgroundColor))
  153. {
  154. using (var originalImage = new MagickWand(inputPath))
  155. {
  156. ScaleImage(originalImage, width, height);
  157. if (autoOrient)
  158. {
  159. AutoOrientImage(originalImage);
  160. }
  161. wand.CurrentImage.CompositeImage(originalImage, CompositeOperator.OverCompositeOp, 0, 0);
  162. AddForegroundLayer(wand, options);
  163. DrawIndicator(wand, width, height, options);
  164. wand.CurrentImage.CompressionQuality = quality;
  165. wand.CurrentImage.StripImage();
  166. wand.SaveImage(outputPath);
  167. }
  168. }
  169. }
  170. }
  171. private void AddForegroundLayer(MagickWand wand, ImageProcessingOptions options)
  172. {
  173. if (string.IsNullOrWhiteSpace(options.ForegroundLayer))
  174. {
  175. return;
  176. }
  177. Double opacity;
  178. if (!Double.TryParse(options.ForegroundLayer, out opacity)) opacity = .4;
  179. using (var pixel = new PixelWand("#000", opacity))
  180. using (var overlay = new MagickWand(wand.CurrentImage.Width, wand.CurrentImage.Height, pixel))
  181. {
  182. wand.CurrentImage.CompositeImage(overlay, CompositeOperator.OverCompositeOp, 0, 0);
  183. }
  184. }
  185. private void AutoOrientImage(MagickWand wand)
  186. {
  187. wand.CurrentImage.AutoOrientImage();
  188. }
  189. public static void RotateImage(MagickWand wand, float angle)
  190. {
  191. using (var pixelWand = new PixelWand("none", 1))
  192. {
  193. wand.CurrentImage.RotateImage(pixelWand, angle);
  194. }
  195. }
  196. private void ScaleImage(MagickWand wand, int width, int height)
  197. {
  198. var highQuality = false;
  199. if (highQuality)
  200. {
  201. wand.CurrentImage.ResizeImage(width, height);
  202. }
  203. else
  204. {
  205. wand.CurrentImage.ScaleImage(width, height);
  206. }
  207. }
  208. /// <summary>
  209. /// Draws the indicator.
  210. /// </summary>
  211. /// <param name="wand">The wand.</param>
  212. /// <param name="imageWidth">Width of the image.</param>
  213. /// <param name="imageHeight">Height of the image.</param>
  214. /// <param name="options">The options.</param>
  215. private void DrawIndicator(MagickWand wand, int imageWidth, int imageHeight, ImageProcessingOptions options)
  216. {
  217. if (!options.AddPlayedIndicator && !options.UnplayedCount.HasValue && options.PercentPlayed.Equals(0))
  218. {
  219. return;
  220. }
  221. try
  222. {
  223. if (options.AddPlayedIndicator)
  224. {
  225. var currentImageSize = new ImageSize(imageWidth, imageHeight);
  226. var task = new PlayedIndicatorDrawer(_appPaths, _httpClient, _fileSystem).DrawPlayedIndicator(wand, currentImageSize);
  227. Task.WaitAll(task);
  228. }
  229. else if (options.UnplayedCount.HasValue)
  230. {
  231. var currentImageSize = new ImageSize(imageWidth, imageHeight);
  232. new UnplayedCountIndicator(_appPaths, _fileSystem).DrawUnplayedCountIndicator(wand, currentImageSize, options.UnplayedCount.Value);
  233. }
  234. if (options.PercentPlayed > 0)
  235. {
  236. new PercentPlayedDrawer().Process(wand, options.PercentPlayed);
  237. }
  238. }
  239. catch (Exception ex)
  240. {
  241. _logger.ErrorException("Error drawing indicator overlay", ex);
  242. }
  243. }
  244. public void CreateImageCollage(ImageCollageOptions options)
  245. {
  246. double ratio = options.Width;
  247. ratio /= options.Height;
  248. if (ratio >= 1.4)
  249. {
  250. new StripCollageBuilder(_appPaths, _fileSystem).BuildThumbCollage(options.InputPaths.ToList(), options.OutputPath, options.Width, options.Height);
  251. }
  252. else if (ratio >= .9)
  253. {
  254. new StripCollageBuilder(_appPaths, _fileSystem).BuildSquareCollage(options.InputPaths.ToList(), options.OutputPath, options.Width, options.Height);
  255. }
  256. else
  257. {
  258. new StripCollageBuilder(_appPaths, _fileSystem).BuildPosterCollage(options.InputPaths.ToList(), options.OutputPath, options.Width, options.Height);
  259. }
  260. }
  261. public string Name
  262. {
  263. get { return "ImageMagick"; }
  264. }
  265. private bool _disposed;
  266. public void Dispose()
  267. {
  268. _disposed = true;
  269. Wand.CloseEnvironment();
  270. }
  271. private void CheckDisposed()
  272. {
  273. if (_disposed)
  274. {
  275. throw new ObjectDisposedException(GetType().Name);
  276. }
  277. }
  278. public bool SupportsImageCollageCreation
  279. {
  280. get { return true; }
  281. }
  282. public bool SupportsImageEncoding
  283. {
  284. get { return true; }
  285. }
  286. }
  287. }