ImageMagickEncoder.cs 11 KB

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