2
0

ImageMagickEncoder.cs 9.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289
  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 CommonIO;
  12. using MediaBrowser.Controller.Configuration;
  13. namespace Emby.Drawing.ImageMagick
  14. {
  15. public class ImageMagickEncoder : IImageEncoder
  16. {
  17. private readonly ILogger _logger;
  18. private readonly IApplicationPaths _appPaths;
  19. private readonly IHttpClient _httpClient;
  20. private readonly IFileSystem _fileSystem;
  21. private readonly IServerConfigurationManager _config;
  22. public ImageMagickEncoder(ILogger logger, IApplicationPaths appPaths, IHttpClient httpClient, IFileSystem fileSystem, IServerConfigurationManager config)
  23. {
  24. _logger = logger;
  25. _appPaths = appPaths;
  26. _httpClient = httpClient;
  27. _fileSystem = fileSystem;
  28. _config = config;
  29. LogVersion();
  30. }
  31. public string[] SupportedInputFormats
  32. {
  33. get
  34. {
  35. // Some common file name extensions for RAW picture files include: .cr2, .crw, .dng, .nef, .orf, .rw2, .pef, .arw, .sr2, .srf, and .tif.
  36. return new[]
  37. {
  38. "tiff",
  39. "jpeg",
  40. "jpg",
  41. "png",
  42. "aiff",
  43. "cr2",
  44. "crw",
  45. "dng",
  46. "nef",
  47. "orf",
  48. "pef",
  49. "arw",
  50. "webp",
  51. "gif",
  52. "bmp"
  53. };
  54. }
  55. }
  56. public ImageFormat[] SupportedOutputFormats
  57. {
  58. get
  59. {
  60. if (_webpAvailable)
  61. {
  62. return new[] { ImageFormat.Webp, ImageFormat.Gif, ImageFormat.Jpg, ImageFormat.Png };
  63. }
  64. return new[] { ImageFormat.Gif, ImageFormat.Jpg, ImageFormat.Png };
  65. }
  66. }
  67. private void LogVersion()
  68. {
  69. _logger.Info("ImageMagick version: " + Wand.VersionString);
  70. TestWebp();
  71. Wand.SetMagickThreadCount(1);
  72. }
  73. private bool _webpAvailable = true;
  74. private void TestWebp()
  75. {
  76. try
  77. {
  78. var tmpPath = Path.Combine(_appPaths.TempDirectory, Guid.NewGuid() + ".webp");
  79. _fileSystem.CreateDirectory(Path.GetDirectoryName(tmpPath));
  80. using (var wand = new MagickWand(1, 1, new PixelWand("none", 1)))
  81. {
  82. wand.SaveImage(tmpPath);
  83. }
  84. }
  85. catch
  86. {
  87. //_logger.ErrorException("Error loading webp: ", ex);
  88. _webpAvailable = false;
  89. }
  90. }
  91. public void CropWhiteSpace(string inputPath, string outputPath)
  92. {
  93. CheckDisposed();
  94. using (var wand = new MagickWand(inputPath))
  95. {
  96. wand.CurrentImage.TrimImage(10);
  97. wand.SaveImage(outputPath);
  98. }
  99. SaveDelay();
  100. }
  101. public ImageSize GetImageSize(string path)
  102. {
  103. CheckDisposed();
  104. using (var wand = new MagickWand())
  105. {
  106. wand.PingImage(path);
  107. var img = wand.CurrentImage;
  108. return new ImageSize
  109. {
  110. Width = img.Width,
  111. Height = img.Height
  112. };
  113. }
  114. }
  115. private bool HasTransparency(string path)
  116. {
  117. var ext = Path.GetExtension(path);
  118. return string.Equals(ext, ".png", StringComparison.OrdinalIgnoreCase) ||
  119. string.Equals(ext, ".webp", StringComparison.OrdinalIgnoreCase);
  120. }
  121. public void EncodeImage(string inputPath, string outputPath, int width, int height, int quality, ImageProcessingOptions options, ImageFormat selectedOutputFormat)
  122. {
  123. // Even if the caller specified 100, don't use it because it takes forever
  124. quality = Math.Min(quality, 99);
  125. if (string.IsNullOrWhiteSpace(options.BackgroundColor) || !HasTransparency(inputPath))
  126. {
  127. using (var originalImage = new MagickWand(inputPath))
  128. {
  129. ScaleImage(originalImage, width, height);
  130. DrawIndicator(originalImage, width, height, options);
  131. originalImage.CurrentImage.CompressionQuality = quality;
  132. //originalImage.CurrentImage.StripImage();
  133. originalImage.SaveImage(outputPath);
  134. }
  135. }
  136. else
  137. {
  138. using (var wand = new MagickWand(width, height, options.BackgroundColor))
  139. {
  140. using (var originalImage = new MagickWand(inputPath))
  141. {
  142. ScaleImage(originalImage, width, height);
  143. wand.CurrentImage.CompositeImage(originalImage, CompositeOperator.OverCompositeOp, 0, 0);
  144. DrawIndicator(wand, width, height, options);
  145. wand.CurrentImage.CompressionQuality = quality;
  146. //wand.CurrentImage.StripImage();
  147. wand.SaveImage(outputPath);
  148. }
  149. }
  150. }
  151. SaveDelay();
  152. }
  153. private void ScaleImage(MagickWand wand, int width, int height)
  154. {
  155. wand.CurrentImage.ResizeImage(width, height);
  156. //if (_config.Configuration.EnableHighQualityImageScaling)
  157. //{
  158. // wand.CurrentImage.ResizeImage(width, height);
  159. //}
  160. //else
  161. //{
  162. // wand.CurrentImage.ScaleImage(width, height);
  163. //}
  164. }
  165. /// <summary>
  166. /// Draws the indicator.
  167. /// </summary>
  168. /// <param name="wand">The wand.</param>
  169. /// <param name="imageWidth">Width of the image.</param>
  170. /// <param name="imageHeight">Height of the image.</param>
  171. /// <param name="options">The options.</param>
  172. private void DrawIndicator(MagickWand wand, int imageWidth, int imageHeight, ImageProcessingOptions options)
  173. {
  174. if (!options.AddPlayedIndicator && !options.UnplayedCount.HasValue && options.PercentPlayed.Equals(0))
  175. {
  176. return;
  177. }
  178. try
  179. {
  180. if (options.AddPlayedIndicator)
  181. {
  182. var currentImageSize = new ImageSize(imageWidth, imageHeight);
  183. var task = new PlayedIndicatorDrawer(_appPaths, _httpClient, _fileSystem).DrawPlayedIndicator(wand, currentImageSize);
  184. Task.WaitAll(task);
  185. }
  186. else if (options.UnplayedCount.HasValue)
  187. {
  188. var currentImageSize = new ImageSize(imageWidth, imageHeight);
  189. new UnplayedCountIndicator(_appPaths, _fileSystem).DrawUnplayedCountIndicator(wand, currentImageSize, options.UnplayedCount.Value);
  190. }
  191. if (options.PercentPlayed > 0)
  192. {
  193. new PercentPlayedDrawer().Process(wand, options.PercentPlayed);
  194. }
  195. }
  196. catch (Exception ex)
  197. {
  198. _logger.ErrorException("Error drawing indicator overlay", ex);
  199. }
  200. }
  201. public void CreateImageCollage(ImageCollageOptions options)
  202. {
  203. double ratio = options.Width;
  204. ratio /= options.Height;
  205. if (ratio >= 1.4)
  206. {
  207. new StripCollageBuilder(_appPaths, _fileSystem).BuildThumbCollage(options.InputPaths.ToList(), options.OutputPath, options.Width, options.Height, options.Text);
  208. }
  209. else if (ratio >= .9)
  210. {
  211. new StripCollageBuilder(_appPaths, _fileSystem).BuildSquareCollage(options.InputPaths.ToList(), options.OutputPath, options.Width, options.Height, options.Text);
  212. }
  213. else
  214. {
  215. new StripCollageBuilder(_appPaths, _fileSystem).BuildPosterCollage(options.InputPaths.ToList(), options.OutputPath, options.Width, options.Height, options.Text);
  216. }
  217. SaveDelay();
  218. }
  219. private void SaveDelay()
  220. {
  221. // For some reason the images are not always getting released right away
  222. //var task = Task.Delay(300);
  223. //Task.WaitAll(task);
  224. }
  225. public string Name
  226. {
  227. get { return "ImageMagick"; }
  228. }
  229. private bool _disposed;
  230. public void Dispose()
  231. {
  232. _disposed = true;
  233. Wand.CloseEnvironment();
  234. }
  235. private void CheckDisposed()
  236. {
  237. if (_disposed)
  238. {
  239. throw new ObjectDisposedException(GetType().Name);
  240. }
  241. }
  242. public bool SupportsImageCollageCreation
  243. {
  244. get { return true; }
  245. }
  246. public bool SupportsImageEncoding
  247. {
  248. get { return true; }
  249. }
  250. }
  251. }