ImageMagickEncoder.cs 10 KB

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