ImageMagickEncoder.cs 12 KB

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