ImageMagickEncoder.cs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348
  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 string EncodeImage(string inputPath, DateTime dateModified, 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. var originalImageSize = new ImageSize(originalImage.CurrentImage.Width, originalImage.CurrentImage.Height);
  130. ImageHelper.SaveImageSize(inputPath, dateModified, originalImageSize);
  131. if (!options.CropWhiteSpace && options.HasDefaultOptions(inputPath, originalImageSize))
  132. {
  133. // Just spit out the original file if all the options are default
  134. return inputPath;
  135. }
  136. var newImageSize = ImageHelper.GetNewImageSize(options, originalImageSize);
  137. var width = Convert.ToInt32(Math.Round(newImageSize.Width));
  138. var height = Convert.ToInt32(Math.Round(newImageSize.Height));
  139. ScaleImage(originalImage, width, height, options.Blur ?? 0);
  140. if (autoOrient)
  141. {
  142. AutoOrientImage(originalImage);
  143. }
  144. AddForegroundLayer(originalImage, options);
  145. DrawIndicator(originalImage, width, height, options);
  146. originalImage.CurrentImage.CompressionQuality = quality;
  147. originalImage.CurrentImage.StripImage();
  148. originalImage.SaveImage(outputPath);
  149. }
  150. }
  151. else
  152. {
  153. using (var originalImage = new MagickWand(inputPath))
  154. {
  155. var originalImageSize = new ImageSize(originalImage.CurrentImage.Width, originalImage.CurrentImage.Height);
  156. ImageHelper.SaveImageSize(inputPath, dateModified, originalImageSize);
  157. var newImageSize = ImageHelper.GetNewImageSize(options, originalImageSize);
  158. var width = Convert.ToInt32(Math.Round(newImageSize.Width));
  159. var height = Convert.ToInt32(Math.Round(newImageSize.Height));
  160. using (var wand = new MagickWand(width, height, options.BackgroundColor))
  161. {
  162. ScaleImage(originalImage, width, height, options.Blur ?? 0);
  163. if (autoOrient)
  164. {
  165. AutoOrientImage(originalImage);
  166. }
  167. wand.CurrentImage.CompositeImage(originalImage, CompositeOperator.OverCompositeOp, 0, 0);
  168. AddForegroundLayer(wand, options);
  169. DrawIndicator(wand, width, height, options);
  170. wand.CurrentImage.CompressionQuality = quality;
  171. wand.CurrentImage.StripImage();
  172. wand.SaveImage(outputPath);
  173. }
  174. }
  175. }
  176. return outputPath;
  177. }
  178. private void AddForegroundLayer(MagickWand wand, ImageProcessingOptions options)
  179. {
  180. if (string.IsNullOrWhiteSpace(options.ForegroundLayer))
  181. {
  182. return;
  183. }
  184. Double opacity;
  185. if (!Double.TryParse(options.ForegroundLayer, out opacity)) opacity = .4;
  186. using (var pixel = new PixelWand("#000", opacity))
  187. using (var overlay = new MagickWand(wand.CurrentImage.Width, wand.CurrentImage.Height, pixel))
  188. {
  189. wand.CurrentImage.CompositeImage(overlay, CompositeOperator.OverCompositeOp, 0, 0);
  190. }
  191. }
  192. private void AutoOrientImage(MagickWand wand)
  193. {
  194. wand.CurrentImage.AutoOrientImage();
  195. }
  196. public static void RotateImage(MagickWand wand, float angle)
  197. {
  198. using (var pixelWand = new PixelWand("none", 1))
  199. {
  200. wand.CurrentImage.RotateImage(pixelWand, angle);
  201. }
  202. }
  203. private void ScaleImage(MagickWand wand, int width, int height, int blur)
  204. {
  205. var useResize = blur > 1;
  206. if (useResize)
  207. {
  208. wand.CurrentImage.ResizeImage(width, height, FilterTypes.GaussianFilter, blur);
  209. }
  210. else
  211. {
  212. wand.CurrentImage.ScaleImage(width, height);
  213. }
  214. }
  215. /// <summary>
  216. /// Draws the indicator.
  217. /// </summary>
  218. /// <param name="wand">The wand.</param>
  219. /// <param name="imageWidth">Width of the image.</param>
  220. /// <param name="imageHeight">Height of the image.</param>
  221. /// <param name="options">The options.</param>
  222. private void DrawIndicator(MagickWand wand, int imageWidth, int imageHeight, ImageProcessingOptions options)
  223. {
  224. if (!options.AddPlayedIndicator && !options.UnplayedCount.HasValue && options.PercentPlayed.Equals(0))
  225. {
  226. return;
  227. }
  228. try
  229. {
  230. if (options.AddPlayedIndicator)
  231. {
  232. var currentImageSize = new ImageSize(imageWidth, imageHeight);
  233. var task = new PlayedIndicatorDrawer(_appPaths, _httpClientFactory(), _fileSystem).DrawPlayedIndicator(wand, currentImageSize);
  234. Task.WaitAll(task);
  235. }
  236. else if (options.UnplayedCount.HasValue)
  237. {
  238. var currentImageSize = new ImageSize(imageWidth, imageHeight);
  239. new UnplayedCountIndicator(_appPaths, _fileSystem).DrawUnplayedCountIndicator(wand, currentImageSize, options.UnplayedCount.Value);
  240. }
  241. if (options.PercentPlayed > 0)
  242. {
  243. new PercentPlayedDrawer().Process(wand, options.PercentPlayed);
  244. }
  245. }
  246. catch (Exception ex)
  247. {
  248. _logger.ErrorException("Error drawing indicator overlay", ex);
  249. }
  250. }
  251. public void CreateImageCollage(ImageCollageOptions options)
  252. {
  253. double ratio = options.Width;
  254. ratio /= options.Height;
  255. if (ratio >= 1.4)
  256. {
  257. new StripCollageBuilder(_appPaths, _fileSystem).BuildThumbCollage(options.InputPaths.ToList(), options.OutputPath, options.Width, options.Height);
  258. }
  259. else if (ratio >= .9)
  260. {
  261. new StripCollageBuilder(_appPaths, _fileSystem).BuildSquareCollage(options.InputPaths.ToList(), options.OutputPath, options.Width, options.Height);
  262. }
  263. else
  264. {
  265. new StripCollageBuilder(_appPaths, _fileSystem).BuildPosterCollage(options.InputPaths.ToList(), options.OutputPath, options.Width, options.Height);
  266. }
  267. }
  268. public string Name
  269. {
  270. get { return "ImageMagick"; }
  271. }
  272. private bool _disposed;
  273. public void Dispose()
  274. {
  275. _disposed = true;
  276. Wand.CloseEnvironment();
  277. }
  278. private void CheckDisposed()
  279. {
  280. if (_disposed)
  281. {
  282. throw new ObjectDisposedException(GetType().Name);
  283. }
  284. }
  285. public bool SupportsImageCollageCreation
  286. {
  287. get { return true; }
  288. }
  289. public bool SupportsImageEncoding
  290. {
  291. get { return true; }
  292. }
  293. }
  294. }