ImageMagickEncoder.cs 10 KB

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