ImageMagickEncoder.cs 8.0 KB

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