ImageMagickEncoder.cs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354
  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 MediaBrowser.Model.IO;
  11. using MediaBrowser.Model.System;
  12. namespace Emby.Drawing.ImageMagick
  13. {
  14. public class ImageMagickEncoder : IImageEncoder, IDisposable
  15. {
  16. private readonly ILogger _logger;
  17. private readonly IApplicationPaths _appPaths;
  18. private readonly Func<IHttpClient> _httpClientFactory;
  19. private readonly IFileSystem _fileSystem;
  20. private readonly IEnvironmentInfo _environment;
  21. public ImageMagickEncoder(ILogger logger, IApplicationPaths appPaths, Func<IHttpClient> httpClientFactory, IFileSystem fileSystem, IEnvironmentInfo environment)
  22. {
  23. _logger = logger;
  24. _appPaths = appPaths;
  25. _httpClientFactory = httpClientFactory;
  26. _fileSystem = fileSystem;
  27. _environment = environment;
  28. LogVersion();
  29. }
  30. public string[] SupportedInputFormats
  31. {
  32. get
  33. {
  34. // Some common file name extensions for RAW picture files include: .cr2, .crw, .dng, .nef, .orf, .rw2, .pef, .arw, .sr2, .srf, and .tif.
  35. return new[]
  36. {
  37. "tiff",
  38. "tif",
  39. "jpeg",
  40. "jpg",
  41. "png",
  42. "aiff",
  43. "cr2",
  44. "crw",
  45. "dng",
  46. // Remove until supported
  47. //"nef",
  48. "orf",
  49. "pef",
  50. "arw",
  51. "webp",
  52. "gif",
  53. "bmp",
  54. "erf",
  55. "raf",
  56. "rw2",
  57. "nrw"
  58. };
  59. }
  60. }
  61. public ImageFormat[] SupportedOutputFormats
  62. {
  63. get
  64. {
  65. if (_webpAvailable)
  66. {
  67. return new[] { ImageFormat.Webp, ImageFormat.Gif, ImageFormat.Jpg, ImageFormat.Png };
  68. }
  69. return new[] { ImageFormat.Gif, ImageFormat.Jpg, ImageFormat.Png };
  70. }
  71. }
  72. private void LogVersion()
  73. {
  74. _logger.Info("ImageMagick version: " + GetVersion());
  75. TestWebp();
  76. Wand.SetMagickThreadCount(1);
  77. }
  78. public static string GetVersion()
  79. {
  80. return Wand.VersionString;
  81. }
  82. private bool _webpAvailable = true;
  83. private void TestWebp()
  84. {
  85. try
  86. {
  87. var tmpPath = Path.Combine(_appPaths.TempDirectory, Guid.NewGuid() + ".webp");
  88. _fileSystem.CreateDirectory(_fileSystem.GetDirectoryName(tmpPath));
  89. using (var wand = new MagickWand(1, 1, new PixelWand("none", 1)))
  90. {
  91. wand.SaveImage(tmpPath);
  92. }
  93. }
  94. catch
  95. {
  96. //_logger.ErrorException("Error loading webp: ", ex);
  97. _webpAvailable = false;
  98. }
  99. }
  100. public ImageSize GetImageSize(string path)
  101. {
  102. CheckDisposed();
  103. using (var wand = new MagickWand())
  104. {
  105. wand.PingImage(path);
  106. var img = wand.CurrentImage;
  107. return new ImageSize
  108. {
  109. Width = img.Width,
  110. Height = img.Height
  111. };
  112. }
  113. }
  114. private bool HasTransparency(string path)
  115. {
  116. var ext = Path.GetExtension(path);
  117. return string.Equals(ext, ".png", StringComparison.OrdinalIgnoreCase) ||
  118. string.Equals(ext, ".webp", StringComparison.OrdinalIgnoreCase);
  119. }
  120. public string EncodeImage(string inputPath, DateTime dateModified, string outputPath, bool autoOrient, ImageOrientation? orientation, int quality, ImageProcessingOptions options, ImageFormat selectedOutputFormat)
  121. {
  122. // Even if the caller specified 100, don't use it because it takes forever
  123. quality = Math.Min(quality, 99);
  124. if (string.IsNullOrEmpty(options.BackgroundColor) || !HasTransparency(inputPath))
  125. {
  126. using (var originalImage = new MagickWand(inputPath))
  127. {
  128. if (options.CropWhiteSpace)
  129. {
  130. originalImage.CurrentImage.TrimImage(10);
  131. }
  132. var originalImageSize = new ImageSize(originalImage.CurrentImage.Width, originalImage.CurrentImage.Height);
  133. if (!options.CropWhiteSpace && options.HasDefaultOptions(inputPath, originalImageSize) && !autoOrient)
  134. {
  135. // Just spit out the original file if all the options are default
  136. return inputPath;
  137. }
  138. var newImageSize = ImageHelper.GetNewImageSize(options, originalImageSize);
  139. var width = Convert.ToInt32(Math.Round(newImageSize.Width));
  140. var height = Convert.ToInt32(Math.Round(newImageSize.Height));
  141. ScaleImage(originalImage, width, height, options.Blur ?? 0);
  142. if (autoOrient)
  143. {
  144. AutoOrientImage(originalImage);
  145. }
  146. AddForegroundLayer(originalImage, options);
  147. DrawIndicator(originalImage, width, height, options);
  148. originalImage.CurrentImage.CompressionQuality = quality;
  149. originalImage.CurrentImage.StripImage();
  150. _fileSystem.CreateDirectory(_fileSystem.GetDirectoryName(outputPath));
  151. originalImage.SaveImage(outputPath);
  152. }
  153. }
  154. else
  155. {
  156. using (var originalImage = new MagickWand(inputPath))
  157. {
  158. var originalImageSize = new ImageSize(originalImage.CurrentImage.Width, originalImage.CurrentImage.Height);
  159. var newImageSize = ImageHelper.GetNewImageSize(options, originalImageSize);
  160. var width = Convert.ToInt32(Math.Round(newImageSize.Width));
  161. var height = Convert.ToInt32(Math.Round(newImageSize.Height));
  162. using (var wand = new MagickWand(width, height, options.BackgroundColor))
  163. {
  164. ScaleImage(originalImage, width, height, options.Blur ?? 0);
  165. if (autoOrient)
  166. {
  167. AutoOrientImage(originalImage);
  168. }
  169. wand.CurrentImage.CompositeImage(originalImage, CompositeOperator.OverCompositeOp, 0, 0);
  170. AddForegroundLayer(wand, options);
  171. DrawIndicator(wand, width, height, options);
  172. wand.CurrentImage.CompressionQuality = quality;
  173. wand.CurrentImage.StripImage();
  174. wand.SaveImage(outputPath);
  175. }
  176. }
  177. }
  178. return outputPath;
  179. }
  180. private void AddForegroundLayer(MagickWand wand, ImageProcessingOptions options)
  181. {
  182. if (string.IsNullOrEmpty(options.ForegroundLayer))
  183. {
  184. return;
  185. }
  186. Double opacity;
  187. if (!Double.TryParse(options.ForegroundLayer, out opacity)) opacity = .4;
  188. using (var pixel = new PixelWand("#000", opacity))
  189. using (var overlay = new MagickWand(wand.CurrentImage.Width, wand.CurrentImage.Height, pixel))
  190. {
  191. wand.CurrentImage.CompositeImage(overlay, CompositeOperator.OverCompositeOp, 0, 0);
  192. }
  193. }
  194. private void AutoOrientImage(MagickWand wand)
  195. {
  196. wand.CurrentImage.AutoOrientImage();
  197. }
  198. public static void RotateImage(MagickWand wand, float angle)
  199. {
  200. using (var pixelWand = new PixelWand("none", 1))
  201. {
  202. wand.CurrentImage.RotateImage(pixelWand, angle);
  203. }
  204. }
  205. private void ScaleImage(MagickWand wand, int width, int height, int blur)
  206. {
  207. var useResize = blur > 1;
  208. if (useResize)
  209. {
  210. wand.CurrentImage.ResizeImage(width, height, FilterTypes.GaussianFilter, blur);
  211. }
  212. else
  213. {
  214. wand.CurrentImage.ScaleImage(width, height);
  215. }
  216. }
  217. /// <summary>
  218. /// Draws the indicator.
  219. /// </summary>
  220. /// <param name="wand">The wand.</param>
  221. /// <param name="imageWidth">Width of the image.</param>
  222. /// <param name="imageHeight">Height of the image.</param>
  223. /// <param name="options">The options.</param>
  224. private void DrawIndicator(MagickWand wand, int imageWidth, int imageHeight, ImageProcessingOptions options)
  225. {
  226. if (!options.AddPlayedIndicator && !options.UnplayedCount.HasValue && options.PercentPlayed.Equals(0))
  227. {
  228. return;
  229. }
  230. try
  231. {
  232. if (options.AddPlayedIndicator)
  233. {
  234. var currentImageSize = new ImageSize(imageWidth, imageHeight);
  235. var task = new PlayedIndicatorDrawer(_appPaths, _httpClientFactory(), _fileSystem).DrawPlayedIndicator(wand, currentImageSize);
  236. Task.WaitAll(task);
  237. }
  238. else if (options.UnplayedCount.HasValue)
  239. {
  240. var currentImageSize = new ImageSize(imageWidth, imageHeight);
  241. new UnplayedCountIndicator(_appPaths, _fileSystem).DrawUnplayedCountIndicator(wand, currentImageSize, options.UnplayedCount.Value);
  242. }
  243. if (options.PercentPlayed > 0)
  244. {
  245. new PercentPlayedDrawer().Process(wand, options.PercentPlayed);
  246. }
  247. }
  248. catch (Exception ex)
  249. {
  250. _logger.ErrorException("Error drawing indicator overlay", ex);
  251. }
  252. }
  253. public void CreateImageCollage(ImageCollageOptions options)
  254. {
  255. double ratio = options.Width;
  256. ratio /= options.Height;
  257. if (ratio >= 1.4)
  258. {
  259. new StripCollageBuilder(_appPaths, _fileSystem).BuildThumbCollage(options.InputPaths, options.OutputPath, options.Width, options.Height);
  260. }
  261. else if (ratio >= .9)
  262. {
  263. new StripCollageBuilder(_appPaths, _fileSystem).BuildSquareCollage(options.InputPaths, options.OutputPath, options.Width, options.Height);
  264. }
  265. else
  266. {
  267. new StripCollageBuilder(_appPaths, _fileSystem).BuildPosterCollage(options.InputPaths, options.OutputPath, options.Width, options.Height);
  268. }
  269. }
  270. public string Name
  271. {
  272. get { return "ImageMagick"; }
  273. }
  274. private bool _disposed;
  275. public void Dispose()
  276. {
  277. _disposed = true;
  278. Wand.CloseEnvironment();
  279. }
  280. private void CheckDisposed()
  281. {
  282. if (_disposed)
  283. {
  284. throw new ObjectDisposedException(GetType().Name);
  285. }
  286. }
  287. public bool SupportsImageCollageCreation
  288. {
  289. get
  290. {
  291. return true;
  292. }
  293. }
  294. public bool SupportsImageEncoding
  295. {
  296. get { return true; }
  297. }
  298. }
  299. }