ImageProcessor.cs 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834
  1. using ImageMagickSharp;
  2. using MediaBrowser.Common.Extensions;
  3. using MediaBrowser.Common.IO;
  4. using MediaBrowser.Controller;
  5. using MediaBrowser.Controller.Drawing;
  6. using MediaBrowser.Controller.Entities;
  7. using MediaBrowser.Controller.Providers;
  8. using MediaBrowser.Model.Drawing;
  9. using MediaBrowser.Model.Entities;
  10. using MediaBrowser.Model.Logging;
  11. using MediaBrowser.Model.Serialization;
  12. using System;
  13. using System.Collections.Concurrent;
  14. using System.Collections.Generic;
  15. using System.Globalization;
  16. using System.IO;
  17. using System.Linq;
  18. using System.Threading;
  19. using System.Threading.Tasks;
  20. namespace MediaBrowser.Server.Implementations.Drawing
  21. {
  22. /// <summary>
  23. /// Class ImageProcessor
  24. /// </summary>
  25. public class ImageProcessor : IImageProcessor, IDisposable
  26. {
  27. /// <summary>
  28. /// The us culture
  29. /// </summary>
  30. protected readonly CultureInfo UsCulture = new CultureInfo("en-US");
  31. /// <summary>
  32. /// The _cached imaged sizes
  33. /// </summary>
  34. private readonly ConcurrentDictionary<Guid, ImageSize> _cachedImagedSizes;
  35. /// <summary>
  36. /// Gets the list of currently registered image processors
  37. /// Image processors are specialized metadata providers that run after the normal ones
  38. /// </summary>
  39. /// <value>The image enhancers.</value>
  40. public IEnumerable<IImageEnhancer> ImageEnhancers { get; private set; }
  41. /// <summary>
  42. /// The _logger
  43. /// </summary>
  44. private readonly ILogger _logger;
  45. private readonly IFileSystem _fileSystem;
  46. private readonly IJsonSerializer _jsonSerializer;
  47. private readonly IServerApplicationPaths _appPaths;
  48. public ImageProcessor(ILogger logger, IServerApplicationPaths appPaths, IFileSystem fileSystem, IJsonSerializer jsonSerializer)
  49. {
  50. _logger = logger;
  51. _fileSystem = fileSystem;
  52. _jsonSerializer = jsonSerializer;
  53. _appPaths = appPaths;
  54. _saveImageSizeTimer = new Timer(SaveImageSizeCallback, null, Timeout.Infinite, Timeout.Infinite);
  55. Dictionary<Guid, ImageSize> sizeDictionary;
  56. try
  57. {
  58. sizeDictionary = jsonSerializer.DeserializeFromFile<Dictionary<Guid, ImageSize>>(ImageSizeFile) ??
  59. new Dictionary<Guid, ImageSize>();
  60. }
  61. catch (FileNotFoundException)
  62. {
  63. // No biggie
  64. sizeDictionary = new Dictionary<Guid, ImageSize>();
  65. }
  66. catch (DirectoryNotFoundException)
  67. {
  68. // No biggie
  69. sizeDictionary = new Dictionary<Guid, ImageSize>();
  70. }
  71. catch (Exception ex)
  72. {
  73. logger.ErrorException("Error parsing image size cache file", ex);
  74. sizeDictionary = new Dictionary<Guid, ImageSize>();
  75. }
  76. _cachedImagedSizes = new ConcurrentDictionary<Guid, ImageSize>(sizeDictionary);
  77. LogImageMagickVersionVersion();
  78. }
  79. private string ResizedImageCachePath
  80. {
  81. get
  82. {
  83. return Path.Combine(_appPaths.ImageCachePath, "resized-images");
  84. }
  85. }
  86. private string EnhancedImageCachePath
  87. {
  88. get
  89. {
  90. return Path.Combine(_appPaths.ImageCachePath, "enhanced-images");
  91. }
  92. }
  93. private string CroppedWhitespaceImageCachePath
  94. {
  95. get
  96. {
  97. return Path.Combine(_appPaths.ImageCachePath, "cropped-images");
  98. }
  99. }
  100. public void AddParts(IEnumerable<IImageEnhancer> enhancers)
  101. {
  102. ImageEnhancers = enhancers.ToArray();
  103. }
  104. public async Task ProcessImage(ImageProcessingOptions options, Stream toStream)
  105. {
  106. var file = await ProcessImage(options).ConfigureAwait(false);
  107. using (var fileStream = _fileSystem.GetFileStream(file, FileMode.Open, FileAccess.Read, FileShare.Read, true))
  108. {
  109. await fileStream.CopyToAsync(toStream).ConfigureAwait(false);
  110. }
  111. }
  112. public ImageFormat[] GetSupportedImageOutputFormats()
  113. {
  114. return new[] { ImageFormat.Webp, ImageFormat.Gif, ImageFormat.Jpg, ImageFormat.Png };
  115. }
  116. public async Task<string> ProcessImage(ImageProcessingOptions options)
  117. {
  118. if (options == null)
  119. {
  120. throw new ArgumentNullException("options");
  121. }
  122. var originalImagePath = options.Image.Path;
  123. if (options.HasDefaultOptions(originalImagePath) && options.Enhancers.Count == 0 && !options.CropWhiteSpace)
  124. {
  125. // Just spit out the original file if all the options are default
  126. return originalImagePath;
  127. }
  128. var dateModified = options.Image.DateModified;
  129. if (options.CropWhiteSpace)
  130. {
  131. var tuple = await GetWhitespaceCroppedImage(originalImagePath, dateModified).ConfigureAwait(false);
  132. originalImagePath = tuple.Item1;
  133. dateModified = tuple.Item2;
  134. }
  135. if (options.Enhancers.Count > 0)
  136. {
  137. var tuple = await GetEnhancedImage(options.Image, options.Item, options.ImageIndex, options.Enhancers).ConfigureAwait(false);
  138. originalImagePath = tuple.Item1;
  139. dateModified = tuple.Item2;
  140. }
  141. var originalImageSize = GetImageSize(originalImagePath, dateModified);
  142. // Determine the output size based on incoming parameters
  143. var newSize = DrawingUtils.Resize(originalImageSize, options.Width, options.Height, options.MaxWidth, options.MaxHeight);
  144. if (options.HasDefaultOptionsWithoutSize(originalImagePath) && newSize.Equals(originalImageSize) && options.Enhancers.Count == 0)
  145. {
  146. // Just spit out the original file if the new size equals the old
  147. return originalImagePath;
  148. }
  149. var quality = options.Quality ?? 90;
  150. var cacheFilePath = GetCacheFilePath(originalImagePath, newSize, quality, dateModified, options.OutputFormat, options.AddPlayedIndicator, options.PercentPlayed, options.UnplayedCount, options.BackgroundColor);
  151. var semaphore = GetLock(cacheFilePath);
  152. await semaphore.WaitAsync().ConfigureAwait(false);
  153. // Check again in case of lock contention
  154. try
  155. {
  156. if (File.Exists(cacheFilePath))
  157. {
  158. semaphore.Release();
  159. return cacheFilePath;
  160. }
  161. }
  162. catch
  163. {
  164. semaphore.Release();
  165. throw;
  166. }
  167. try
  168. {
  169. var newWidth = Convert.ToInt32(newSize.Width);
  170. var newHeight = Convert.ToInt32(newSize.Height);
  171. Directory.CreateDirectory(Path.GetDirectoryName(cacheFilePath));
  172. if (string.IsNullOrWhiteSpace(options.BackgroundColor))
  173. {
  174. using (var originalImage = new MagickWand(originalImagePath))
  175. {
  176. originalImage.CurrentImage.ResizeImage(newWidth, newHeight);
  177. DrawIndicator(originalImage, newWidth, newHeight, options);
  178. originalImage.CurrentImage.CompressionQuality = quality;
  179. originalImage.SaveImage(cacheFilePath);
  180. return cacheFilePath;
  181. }
  182. }
  183. else
  184. {
  185. using (var wand = new MagickWand(newWidth, newHeight, options.BackgroundColor))
  186. {
  187. using (var originalImage = new MagickWand(originalImagePath))
  188. {
  189. originalImage.CurrentImage.ResizeImage(newWidth, newHeight);
  190. wand.CurrentImage.CompositeImage(originalImage, CompositeOperator.OverCompositeOp, 0, 0);
  191. DrawIndicator(wand, newWidth, newHeight, options);
  192. wand.CurrentImage.CompressionQuality = quality;
  193. wand.SaveImage(cacheFilePath);
  194. return cacheFilePath;
  195. }
  196. }
  197. }
  198. }
  199. finally
  200. {
  201. semaphore.Release();
  202. }
  203. }
  204. private void LogImageMagickVersionVersion()
  205. {
  206. try
  207. {
  208. _logger.Info("ImageMagick version: " + Wand.VersionString);
  209. }
  210. catch (Exception ex)
  211. {
  212. _logger.ErrorException("Error loading ImageMagick: ", ex);
  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. new PlayedIndicatorDrawer().DrawPlayedIndicator(wand, currentImageSize);
  234. }
  235. else if (options.UnplayedCount.HasValue)
  236. {
  237. var currentImageSize = new ImageSize(imageWidth, imageHeight);
  238. new UnplayedCountIndicator().DrawUnplayedCountIndicator(wand, currentImageSize, options.UnplayedCount.Value);
  239. }
  240. if (options.PercentPlayed > 0)
  241. {
  242. new PercentPlayedDrawer().Process(wand, options.PercentPlayed);
  243. }
  244. }
  245. catch (Exception ex)
  246. {
  247. _logger.ErrorException("Error drawing indicator overlay", ex);
  248. }
  249. }
  250. /// <summary>
  251. /// Crops whitespace from an image, caches the result, and returns the cached path
  252. /// </summary>
  253. /// <param name="originalImagePath">The original image path.</param>
  254. /// <param name="dateModified">The date modified.</param>
  255. /// <returns>System.String.</returns>
  256. private async Task<Tuple<string, DateTime>> GetWhitespaceCroppedImage(string originalImagePath, DateTime dateModified)
  257. {
  258. var name = originalImagePath;
  259. name += "datemodified=" + dateModified.Ticks;
  260. var croppedImagePath = GetCachePath(CroppedWhitespaceImageCachePath, name, Path.GetExtension(originalImagePath));
  261. var semaphore = GetLock(croppedImagePath);
  262. await semaphore.WaitAsync().ConfigureAwait(false);
  263. // Check again in case of contention
  264. if (File.Exists(croppedImagePath))
  265. {
  266. semaphore.Release();
  267. return new Tuple<string, DateTime>(croppedImagePath, _fileSystem.GetLastWriteTimeUtc(croppedImagePath));
  268. }
  269. try
  270. {
  271. Directory.CreateDirectory(Path.GetDirectoryName(croppedImagePath));
  272. using (var wand = new MagickWand(originalImagePath))
  273. {
  274. wand.CurrentImage.TrimImage(10);
  275. wand.SaveImage(croppedImagePath);
  276. }
  277. }
  278. catch (Exception ex)
  279. {
  280. // We have to have a catch-all here because some of the .net image methods throw a plain old Exception
  281. _logger.ErrorException("Error cropping image {0}", ex, originalImagePath);
  282. return new Tuple<string, DateTime>(originalImagePath, dateModified);
  283. }
  284. finally
  285. {
  286. semaphore.Release();
  287. }
  288. return new Tuple<string, DateTime>(croppedImagePath, _fileSystem.GetLastWriteTimeUtc(croppedImagePath));
  289. }
  290. /// <summary>
  291. /// Increment this when indicator drawings change
  292. /// </summary>
  293. private const string IndicatorVersion = "2";
  294. /// <summary>
  295. /// Gets the cache file path based on a set of parameters
  296. /// </summary>
  297. private string GetCacheFilePath(string originalPath, ImageSize outputSize, int quality, DateTime dateModified, ImageFormat format, bool addPlayedIndicator, double percentPlayed, int? unwatchedCount, string backgroundColor)
  298. {
  299. var filename = originalPath;
  300. filename += "width=" + outputSize.Width;
  301. filename += "height=" + outputSize.Height;
  302. filename += "quality=" + quality;
  303. filename += "datemodified=" + dateModified.Ticks;
  304. filename += "f=" + format;
  305. var hasIndicator = false;
  306. if (addPlayedIndicator)
  307. {
  308. filename += "pl=true";
  309. hasIndicator = true;
  310. }
  311. if (percentPlayed > 0)
  312. {
  313. filename += "p=" + percentPlayed;
  314. hasIndicator = true;
  315. }
  316. if (unwatchedCount.HasValue)
  317. {
  318. filename += "p=" + unwatchedCount.Value;
  319. hasIndicator = true;
  320. }
  321. if (hasIndicator)
  322. {
  323. filename += "iv=" + IndicatorVersion;
  324. }
  325. if (!string.IsNullOrEmpty(backgroundColor))
  326. {
  327. filename += "b=" + backgroundColor;
  328. }
  329. return GetCachePath(ResizedImageCachePath, filename, "." + format.ToString().ToLower());
  330. }
  331. /// <summary>
  332. /// Gets the size of the image.
  333. /// </summary>
  334. /// <param name="path">The path.</param>
  335. /// <returns>ImageSize.</returns>
  336. public ImageSize GetImageSize(string path)
  337. {
  338. return GetImageSize(path, File.GetLastWriteTimeUtc(path));
  339. }
  340. public ImageSize GetImageSize(ItemImageInfo info)
  341. {
  342. return GetImageSize(info.Path, info.DateModified);
  343. }
  344. /// <summary>
  345. /// Gets the size of the image.
  346. /// </summary>
  347. /// <param name="path">The path.</param>
  348. /// <param name="imageDateModified">The image date modified.</param>
  349. /// <returns>ImageSize.</returns>
  350. /// <exception cref="System.ArgumentNullException">path</exception>
  351. private ImageSize GetImageSize(string path, DateTime imageDateModified)
  352. {
  353. if (string.IsNullOrEmpty(path))
  354. {
  355. throw new ArgumentNullException("path");
  356. }
  357. var name = path + "datemodified=" + imageDateModified.Ticks;
  358. ImageSize size;
  359. var cacheHash = name.GetMD5();
  360. if (!_cachedImagedSizes.TryGetValue(cacheHash, out size))
  361. {
  362. size = GetImageSizeInternal(path);
  363. _cachedImagedSizes.AddOrUpdate(cacheHash, size, (keyName, oldValue) => size);
  364. }
  365. return size;
  366. }
  367. /// <summary>
  368. /// Gets the image size internal.
  369. /// </summary>
  370. /// <param name="path">The path.</param>
  371. /// <returns>ImageSize.</returns>
  372. private ImageSize GetImageSizeInternal(string path)
  373. {
  374. var size = ImageHeader.GetDimensions(path, _logger, _fileSystem);
  375. StartSaveImageSizeTimer();
  376. return new ImageSize { Width = size.Width, Height = size.Height };
  377. }
  378. private readonly Timer _saveImageSizeTimer;
  379. private const int SaveImageSizeTimeout = 5000;
  380. private readonly object _saveImageSizeLock = new object();
  381. private void StartSaveImageSizeTimer()
  382. {
  383. _saveImageSizeTimer.Change(SaveImageSizeTimeout, Timeout.Infinite);
  384. }
  385. private void SaveImageSizeCallback(object state)
  386. {
  387. lock (_saveImageSizeLock)
  388. {
  389. try
  390. {
  391. var path = ImageSizeFile;
  392. Directory.CreateDirectory(Path.GetDirectoryName(path));
  393. _jsonSerializer.SerializeToFile(_cachedImagedSizes, path);
  394. }
  395. catch (Exception ex)
  396. {
  397. _logger.ErrorException("Error saving image size file", ex);
  398. }
  399. }
  400. }
  401. private string ImageSizeFile
  402. {
  403. get
  404. {
  405. return Path.Combine(_appPaths.DataPath, "imagesizes.json");
  406. }
  407. }
  408. /// <summary>
  409. /// Gets the image cache tag.
  410. /// </summary>
  411. /// <param name="item">The item.</param>
  412. /// <param name="image">The image.</param>
  413. /// <returns>Guid.</returns>
  414. /// <exception cref="System.ArgumentNullException">item</exception>
  415. public string GetImageCacheTag(IHasImages item, ItemImageInfo image)
  416. {
  417. if (item == null)
  418. {
  419. throw new ArgumentNullException("item");
  420. }
  421. if (image == null)
  422. {
  423. throw new ArgumentNullException("image");
  424. }
  425. var supportedEnhancers = GetSupportedEnhancers(item, image.Type);
  426. return GetImageCacheTag(item, image, supportedEnhancers.ToList());
  427. }
  428. /// <summary>
  429. /// Gets the image cache tag.
  430. /// </summary>
  431. /// <param name="item">The item.</param>
  432. /// <param name="image">The image.</param>
  433. /// <param name="imageEnhancers">The image enhancers.</param>
  434. /// <returns>Guid.</returns>
  435. /// <exception cref="System.ArgumentNullException">item</exception>
  436. public string GetImageCacheTag(IHasImages item, ItemImageInfo image, List<IImageEnhancer> imageEnhancers)
  437. {
  438. if (item == null)
  439. {
  440. throw new ArgumentNullException("item");
  441. }
  442. if (imageEnhancers == null)
  443. {
  444. throw new ArgumentNullException("imageEnhancers");
  445. }
  446. if (image == null)
  447. {
  448. throw new ArgumentNullException("image");
  449. }
  450. var originalImagePath = image.Path;
  451. var dateModified = image.DateModified;
  452. var imageType = image.Type;
  453. // Optimization
  454. if (imageEnhancers.Count == 0)
  455. {
  456. return (originalImagePath + dateModified.Ticks).GetMD5().ToString("N");
  457. }
  458. // Cache name is created with supported enhancers combined with the last config change so we pick up new config changes
  459. var cacheKeys = imageEnhancers.Select(i => i.GetConfigurationCacheKey(item, imageType)).ToList();
  460. cacheKeys.Add(originalImagePath + dateModified.Ticks);
  461. return string.Join("|", cacheKeys.ToArray()).GetMD5().ToString("N");
  462. }
  463. /// <summary>
  464. /// Gets the enhanced image.
  465. /// </summary>
  466. /// <param name="item">The item.</param>
  467. /// <param name="imageType">Type of the image.</param>
  468. /// <param name="imageIndex">Index of the image.</param>
  469. /// <returns>Task{System.String}.</returns>
  470. public async Task<string> GetEnhancedImage(IHasImages item, ImageType imageType, int imageIndex)
  471. {
  472. var enhancers = GetSupportedEnhancers(item, imageType).ToList();
  473. var imageInfo = item.GetImageInfo(imageType, imageIndex);
  474. var result = await GetEnhancedImage(imageInfo, item, imageIndex, enhancers);
  475. return result.Item1;
  476. }
  477. private async Task<Tuple<string, DateTime>> GetEnhancedImage(ItemImageInfo image,
  478. IHasImages item,
  479. int imageIndex,
  480. List<IImageEnhancer> enhancers)
  481. {
  482. var originalImagePath = image.Path;
  483. var dateModified = image.DateModified;
  484. var imageType = image.Type;
  485. try
  486. {
  487. var cacheGuid = GetImageCacheTag(item, image, enhancers);
  488. // Enhance if we have enhancers
  489. var ehnancedImagePath = await GetEnhancedImageInternal(originalImagePath, item, imageType, imageIndex, enhancers, cacheGuid).ConfigureAwait(false);
  490. // If the path changed update dateModified
  491. if (!ehnancedImagePath.Equals(originalImagePath, StringComparison.OrdinalIgnoreCase))
  492. {
  493. dateModified = _fileSystem.GetLastWriteTimeUtc(ehnancedImagePath);
  494. return new Tuple<string, DateTime>(ehnancedImagePath, dateModified);
  495. }
  496. }
  497. catch (Exception ex)
  498. {
  499. _logger.Error("Error enhancing image", ex);
  500. }
  501. return new Tuple<string, DateTime>(originalImagePath, dateModified);
  502. }
  503. /// <summary>
  504. /// Gets the enhanced image internal.
  505. /// </summary>
  506. /// <param name="originalImagePath">The original image path.</param>
  507. /// <param name="item">The item.</param>
  508. /// <param name="imageType">Type of the image.</param>
  509. /// <param name="imageIndex">Index of the image.</param>
  510. /// <param name="supportedEnhancers">The supported enhancers.</param>
  511. /// <param name="cacheGuid">The cache unique identifier.</param>
  512. /// <returns>Task&lt;System.String&gt;.</returns>
  513. /// <exception cref="ArgumentNullException">
  514. /// originalImagePath
  515. /// or
  516. /// item
  517. /// </exception>
  518. private async Task<string> GetEnhancedImageInternal(string originalImagePath,
  519. IHasImages item,
  520. ImageType imageType,
  521. int imageIndex,
  522. IEnumerable<IImageEnhancer> supportedEnhancers,
  523. string cacheGuid)
  524. {
  525. if (string.IsNullOrEmpty(originalImagePath))
  526. {
  527. throw new ArgumentNullException("originalImagePath");
  528. }
  529. if (item == null)
  530. {
  531. throw new ArgumentNullException("item");
  532. }
  533. // All enhanced images are saved as png to allow transparency
  534. var enhancedImagePath = GetCachePath(EnhancedImageCachePath, cacheGuid + ".png");
  535. var semaphore = GetLock(enhancedImagePath);
  536. await semaphore.WaitAsync().ConfigureAwait(false);
  537. // Check again in case of contention
  538. if (File.Exists(enhancedImagePath))
  539. {
  540. semaphore.Release();
  541. return enhancedImagePath;
  542. }
  543. try
  544. {
  545. Directory.CreateDirectory(Path.GetDirectoryName(enhancedImagePath));
  546. await ExecuteImageEnhancers(supportedEnhancers, originalImagePath, enhancedImagePath, item, imageType, imageIndex).ConfigureAwait(false);
  547. }
  548. finally
  549. {
  550. semaphore.Release();
  551. }
  552. return enhancedImagePath;
  553. }
  554. private ImageFormat GetFormat(string path)
  555. {
  556. var extension = Path.GetExtension(path);
  557. if (string.Equals(extension, ".png", StringComparison.OrdinalIgnoreCase))
  558. {
  559. return ImageFormat.Png;
  560. }
  561. if (string.Equals(extension, ".gif", StringComparison.OrdinalIgnoreCase))
  562. {
  563. return ImageFormat.Gif;
  564. }
  565. if (string.Equals(extension, ".webp", StringComparison.OrdinalIgnoreCase))
  566. {
  567. return ImageFormat.Webp;
  568. }
  569. if (string.Equals(extension, ".bmp", StringComparison.OrdinalIgnoreCase))
  570. {
  571. return ImageFormat.Bmp;
  572. }
  573. return ImageFormat.Jpg;
  574. }
  575. /// <summary>
  576. /// Executes the image enhancers.
  577. /// </summary>
  578. /// <param name="imageEnhancers">The image enhancers.</param>
  579. /// <param name="inputPath">The input path.</param>
  580. /// <param name="outputPath">The output path.</param>
  581. /// <param name="item">The item.</param>
  582. /// <param name="imageType">Type of the image.</param>
  583. /// <param name="imageIndex">Index of the image.</param>
  584. /// <returns>Task{EnhancedImage}.</returns>
  585. private async Task ExecuteImageEnhancers(IEnumerable<IImageEnhancer> imageEnhancers, string inputPath, string outputPath, IHasImages item, ImageType imageType, int imageIndex)
  586. {
  587. // Run the enhancers sequentially in order of priority
  588. foreach (var enhancer in imageEnhancers)
  589. {
  590. var typeName = enhancer.GetType().Name;
  591. try
  592. {
  593. await enhancer.EnhanceImageAsync(item, inputPath, outputPath, imageType, imageIndex).ConfigureAwait(false);
  594. }
  595. catch (Exception ex)
  596. {
  597. _logger.ErrorException("{0} failed enhancing {1}", ex, typeName, item.Name);
  598. throw;
  599. }
  600. // Feed the output into the next enhancer as input
  601. inputPath = outputPath;
  602. }
  603. }
  604. /// <summary>
  605. /// The _semaphoreLocks
  606. /// </summary>
  607. private readonly ConcurrentDictionary<string, SemaphoreSlim> _semaphoreLocks = new ConcurrentDictionary<string, SemaphoreSlim>();
  608. /// <summary>
  609. /// Gets the lock.
  610. /// </summary>
  611. /// <param name="filename">The filename.</param>
  612. /// <returns>System.Object.</returns>
  613. private SemaphoreSlim GetLock(string filename)
  614. {
  615. return _semaphoreLocks.GetOrAdd(filename, key => new SemaphoreSlim(1, 1));
  616. }
  617. /// <summary>
  618. /// Gets the cache path.
  619. /// </summary>
  620. /// <param name="path">The path.</param>
  621. /// <param name="uniqueName">Name of the unique.</param>
  622. /// <param name="fileExtension">The file extension.</param>
  623. /// <returns>System.String.</returns>
  624. /// <exception cref="System.ArgumentNullException">
  625. /// path
  626. /// or
  627. /// uniqueName
  628. /// or
  629. /// fileExtension
  630. /// </exception>
  631. public string GetCachePath(string path, string uniqueName, string fileExtension)
  632. {
  633. if (string.IsNullOrEmpty(path))
  634. {
  635. throw new ArgumentNullException("path");
  636. }
  637. if (string.IsNullOrEmpty(uniqueName))
  638. {
  639. throw new ArgumentNullException("uniqueName");
  640. }
  641. if (string.IsNullOrEmpty(fileExtension))
  642. {
  643. throw new ArgumentNullException("fileExtension");
  644. }
  645. var filename = uniqueName.GetMD5() + fileExtension;
  646. return GetCachePath(path, filename);
  647. }
  648. /// <summary>
  649. /// Gets the cache path.
  650. /// </summary>
  651. /// <param name="path">The path.</param>
  652. /// <param name="filename">The filename.</param>
  653. /// <returns>System.String.</returns>
  654. /// <exception cref="System.ArgumentNullException">
  655. /// path
  656. /// or
  657. /// filename
  658. /// </exception>
  659. public string GetCachePath(string path, string filename)
  660. {
  661. if (string.IsNullOrEmpty(path))
  662. {
  663. throw new ArgumentNullException("path");
  664. }
  665. if (string.IsNullOrEmpty(filename))
  666. {
  667. throw new ArgumentNullException("filename");
  668. }
  669. var prefix = filename.Substring(0, 1);
  670. path = Path.Combine(path, prefix);
  671. return Path.Combine(path, filename);
  672. }
  673. public IEnumerable<IImageEnhancer> GetSupportedEnhancers(IHasImages item, ImageType imageType)
  674. {
  675. return ImageEnhancers.Where(i =>
  676. {
  677. try
  678. {
  679. return i.Supports(item, imageType);
  680. }
  681. catch (Exception ex)
  682. {
  683. _logger.ErrorException("Error in image enhancer: {0}", ex, i.GetType().Name);
  684. return false;
  685. }
  686. });
  687. }
  688. public void Dispose()
  689. {
  690. Wand.CloseEnvironment();
  691. _saveImageSizeTimer.Dispose();
  692. }
  693. }
  694. }