ImageMagickEncoder.cs 10 KB

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