ImageMagickEncoder.cs 11 KB

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