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