ImageProcessor.cs 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873
  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. if (_webpAvailable)
  115. {
  116. return new[] { ImageFormat.Webp, ImageFormat.Gif, ImageFormat.Jpg, ImageFormat.Png };
  117. }
  118. return new[] { ImageFormat.Gif, ImageFormat.Jpg, ImageFormat.Png };
  119. }
  120. private bool _webpAvailable = true;
  121. private void TestWebp()
  122. {
  123. try
  124. {
  125. var tmpPath = Path.Combine(_appPaths.TempDirectory, Guid.NewGuid() + ".webp");
  126. Directory.CreateDirectory(Path.GetDirectoryName(tmpPath));
  127. using (var wand = new MagickWand(1, 1, new PixelWand("none", 1)))
  128. {
  129. wand.SaveImage(tmpPath);
  130. }
  131. }
  132. catch (Exception ex)
  133. {
  134. _logger.ErrorException("Error loading webp: ", ex);
  135. _webpAvailable = false;
  136. }
  137. }
  138. private void LogImageMagickVersionVersion()
  139. {
  140. try
  141. {
  142. _logger.Info("ImageMagick version: " + Wand.VersionString);
  143. }
  144. catch (Exception ex)
  145. {
  146. _logger.ErrorException("Error loading ImageMagick: ", ex);
  147. }
  148. TestWebp();
  149. }
  150. public async Task<string> ProcessImage(ImageProcessingOptions options)
  151. {
  152. if (options == null)
  153. {
  154. throw new ArgumentNullException("options");
  155. }
  156. var originalImagePath = options.Image.Path;
  157. if (options.HasDefaultOptions(originalImagePath) && options.Enhancers.Count == 0 && !options.CropWhiteSpace)
  158. {
  159. // Just spit out the original file if all the options are default
  160. return originalImagePath;
  161. }
  162. var dateModified = options.Image.DateModified;
  163. if (options.CropWhiteSpace)
  164. {
  165. var tuple = await GetWhitespaceCroppedImage(originalImagePath, dateModified).ConfigureAwait(false);
  166. originalImagePath = tuple.Item1;
  167. dateModified = tuple.Item2;
  168. }
  169. if (options.Enhancers.Count > 0)
  170. {
  171. var tuple = await GetEnhancedImage(options.Image, options.Item, options.ImageIndex, options.Enhancers).ConfigureAwait(false);
  172. originalImagePath = tuple.Item1;
  173. dateModified = tuple.Item2;
  174. }
  175. var originalImageSize = GetImageSize(originalImagePath, dateModified);
  176. // Determine the output size based on incoming parameters
  177. var newSize = DrawingUtils.Resize(originalImageSize, options.Width, options.Height, options.MaxWidth, options.MaxHeight);
  178. if (options.HasDefaultOptionsWithoutSize(originalImagePath) && newSize.Equals(originalImageSize) && options.Enhancers.Count == 0)
  179. {
  180. // Just spit out the original file if the new size equals the old
  181. return originalImagePath;
  182. }
  183. var quality = options.Quality ?? 90;
  184. var outputFormat = GetOutputFormat(options.OutputFormat);
  185. var cacheFilePath = GetCacheFilePath(originalImagePath, newSize, quality, dateModified, outputFormat, options.AddPlayedIndicator, options.PercentPlayed, options.UnplayedCount, options.BackgroundColor);
  186. var semaphore = GetLock(cacheFilePath);
  187. await semaphore.WaitAsync().ConfigureAwait(false);
  188. // Check again in case of lock contention
  189. try
  190. {
  191. if (File.Exists(cacheFilePath))
  192. {
  193. semaphore.Release();
  194. return cacheFilePath;
  195. }
  196. }
  197. catch
  198. {
  199. semaphore.Release();
  200. throw;
  201. }
  202. try
  203. {
  204. CheckDisposed();
  205. var newWidth = Convert.ToInt32(newSize.Width);
  206. var newHeight = Convert.ToInt32(newSize.Height);
  207. Directory.CreateDirectory(Path.GetDirectoryName(cacheFilePath));
  208. if (string.IsNullOrWhiteSpace(options.BackgroundColor))
  209. {
  210. using (var originalImage = new MagickWand(originalImagePath))
  211. {
  212. originalImage.CurrentImage.ResizeImage(newWidth, newHeight);
  213. DrawIndicator(originalImage, newWidth, newHeight, options);
  214. originalImage.CurrentImage.CompressionQuality = quality;
  215. originalImage.SaveImage(cacheFilePath);
  216. return cacheFilePath;
  217. }
  218. }
  219. else
  220. {
  221. using (var wand = new MagickWand(newWidth, newHeight, options.BackgroundColor))
  222. {
  223. using (var originalImage = new MagickWand(originalImagePath))
  224. {
  225. originalImage.CurrentImage.ResizeImage(newWidth, newHeight);
  226. wand.CurrentImage.CompositeImage(originalImage, CompositeOperator.OverCompositeOp, 0, 0);
  227. DrawIndicator(wand, newWidth, newHeight, options);
  228. wand.CurrentImage.CompressionQuality = quality;
  229. wand.SaveImage(cacheFilePath);
  230. return cacheFilePath;
  231. }
  232. }
  233. }
  234. }
  235. finally
  236. {
  237. semaphore.Release();
  238. }
  239. }
  240. private ImageFormat GetOutputFormat(ImageFormat requestedFormat)
  241. {
  242. if (requestedFormat == ImageFormat.Webp && !_webpAvailable)
  243. {
  244. return ImageFormat.Png;
  245. }
  246. return requestedFormat;
  247. }
  248. /// <summary>
  249. /// Draws the indicator.
  250. /// </summary>
  251. /// <param name="wand">The wand.</param>
  252. /// <param name="imageWidth">Width of the image.</param>
  253. /// <param name="imageHeight">Height of the image.</param>
  254. /// <param name="options">The options.</param>
  255. private void DrawIndicator(MagickWand wand, int imageWidth, int imageHeight, ImageProcessingOptions options)
  256. {
  257. if (!options.AddPlayedIndicator && !options.UnplayedCount.HasValue && options.PercentPlayed.Equals(0))
  258. {
  259. return;
  260. }
  261. try
  262. {
  263. if (options.AddPlayedIndicator)
  264. {
  265. var currentImageSize = new ImageSize(imageWidth, imageHeight);
  266. new PlayedIndicatorDrawer(_appPaths).DrawPlayedIndicator(wand, currentImageSize);
  267. }
  268. else if (options.UnplayedCount.HasValue)
  269. {
  270. var currentImageSize = new ImageSize(imageWidth, imageHeight);
  271. new UnplayedCountIndicator(_appPaths).DrawUnplayedCountIndicator(wand, currentImageSize, options.UnplayedCount.Value);
  272. }
  273. if (options.PercentPlayed > 0)
  274. {
  275. new PercentPlayedDrawer().Process(wand, options.PercentPlayed);
  276. }
  277. }
  278. catch (Exception ex)
  279. {
  280. _logger.ErrorException("Error drawing indicator overlay", ex);
  281. }
  282. }
  283. /// <summary>
  284. /// Crops whitespace from an image, caches the result, and returns the cached path
  285. /// </summary>
  286. /// <param name="originalImagePath">The original image path.</param>
  287. /// <param name="dateModified">The date modified.</param>
  288. /// <returns>System.String.</returns>
  289. private async Task<Tuple<string, DateTime>> GetWhitespaceCroppedImage(string originalImagePath, DateTime dateModified)
  290. {
  291. var name = originalImagePath;
  292. name += "datemodified=" + dateModified.Ticks;
  293. var croppedImagePath = GetCachePath(CroppedWhitespaceImageCachePath, name, Path.GetExtension(originalImagePath));
  294. var semaphore = GetLock(croppedImagePath);
  295. await semaphore.WaitAsync().ConfigureAwait(false);
  296. // Check again in case of contention
  297. if (File.Exists(croppedImagePath))
  298. {
  299. semaphore.Release();
  300. return new Tuple<string, DateTime>(croppedImagePath, _fileSystem.GetLastWriteTimeUtc(croppedImagePath));
  301. }
  302. try
  303. {
  304. Directory.CreateDirectory(Path.GetDirectoryName(croppedImagePath));
  305. using (var wand = new MagickWand(originalImagePath))
  306. {
  307. wand.CurrentImage.TrimImage(10);
  308. wand.SaveImage(croppedImagePath);
  309. }
  310. }
  311. catch (Exception ex)
  312. {
  313. // We have to have a catch-all here because some of the .net image methods throw a plain old Exception
  314. _logger.ErrorException("Error cropping image {0}", ex, originalImagePath);
  315. return new Tuple<string, DateTime>(originalImagePath, dateModified);
  316. }
  317. finally
  318. {
  319. semaphore.Release();
  320. }
  321. return new Tuple<string, DateTime>(croppedImagePath, _fileSystem.GetLastWriteTimeUtc(croppedImagePath));
  322. }
  323. /// <summary>
  324. /// Increment this when there's a change requiring caches to be invalidated
  325. /// </summary>
  326. private const string Version = "3";
  327. /// <summary>
  328. /// Gets the cache file path based on a set of parameters
  329. /// </summary>
  330. private string GetCacheFilePath(string originalPath, ImageSize outputSize, int quality, DateTime dateModified, ImageFormat format, bool addPlayedIndicator, double percentPlayed, int? unwatchedCount, string backgroundColor)
  331. {
  332. var filename = originalPath;
  333. filename += "width=" + outputSize.Width;
  334. filename += "height=" + outputSize.Height;
  335. filename += "quality=" + quality;
  336. filename += "datemodified=" + dateModified.Ticks;
  337. filename += "f=" + format;
  338. if (addPlayedIndicator)
  339. {
  340. filename += "pl=true";
  341. }
  342. if (percentPlayed > 0)
  343. {
  344. filename += "p=" + percentPlayed;
  345. }
  346. if (unwatchedCount.HasValue)
  347. {
  348. filename += "p=" + unwatchedCount.Value;
  349. }
  350. if (!string.IsNullOrEmpty(backgroundColor))
  351. {
  352. filename += "b=" + backgroundColor;
  353. }
  354. filename += "v=" + Version;
  355. return GetCachePath(ResizedImageCachePath, filename, "." + format.ToString().ToLower());
  356. }
  357. /// <summary>
  358. /// Gets the size of the image.
  359. /// </summary>
  360. /// <param name="path">The path.</param>
  361. /// <returns>ImageSize.</returns>
  362. public ImageSize GetImageSize(string path)
  363. {
  364. return GetImageSize(path, File.GetLastWriteTimeUtc(path));
  365. }
  366. public ImageSize GetImageSize(ItemImageInfo info)
  367. {
  368. return GetImageSize(info.Path, info.DateModified);
  369. }
  370. /// <summary>
  371. /// Gets the size of the image.
  372. /// </summary>
  373. /// <param name="path">The path.</param>
  374. /// <param name="imageDateModified">The image date modified.</param>
  375. /// <returns>ImageSize.</returns>
  376. /// <exception cref="System.ArgumentNullException">path</exception>
  377. private ImageSize GetImageSize(string path, DateTime imageDateModified)
  378. {
  379. if (string.IsNullOrEmpty(path))
  380. {
  381. throw new ArgumentNullException("path");
  382. }
  383. var name = path + "datemodified=" + imageDateModified.Ticks;
  384. ImageSize size;
  385. var cacheHash = name.GetMD5();
  386. if (!_cachedImagedSizes.TryGetValue(cacheHash, out size))
  387. {
  388. size = GetImageSizeInternal(path);
  389. _cachedImagedSizes.AddOrUpdate(cacheHash, size, (keyName, oldValue) => size);
  390. }
  391. return size;
  392. }
  393. /// <summary>
  394. /// Gets the image size internal.
  395. /// </summary>
  396. /// <param name="path">The path.</param>
  397. /// <returns>ImageSize.</returns>
  398. private ImageSize GetImageSizeInternal(string path)
  399. {
  400. ImageSize size;
  401. try
  402. {
  403. size = ImageHeader.GetDimensions(path, _logger, _fileSystem);
  404. }
  405. catch
  406. {
  407. _logger.Info("Failed to read image header for {0}. Doing it the slow way.", path);
  408. CheckDisposed();
  409. using (var wand = new MagickWand())
  410. {
  411. wand.PingImage(path);
  412. var img = wand.CurrentImage;
  413. size = new ImageSize
  414. {
  415. Width = img.Width,
  416. Height = img.Height
  417. };
  418. }
  419. }
  420. StartSaveImageSizeTimer();
  421. return size;
  422. }
  423. private readonly Timer _saveImageSizeTimer;
  424. private const int SaveImageSizeTimeout = 5000;
  425. private readonly object _saveImageSizeLock = new object();
  426. private void StartSaveImageSizeTimer()
  427. {
  428. _saveImageSizeTimer.Change(SaveImageSizeTimeout, Timeout.Infinite);
  429. }
  430. private void SaveImageSizeCallback(object state)
  431. {
  432. lock (_saveImageSizeLock)
  433. {
  434. try
  435. {
  436. var path = ImageSizeFile;
  437. Directory.CreateDirectory(Path.GetDirectoryName(path));
  438. _jsonSerializer.SerializeToFile(_cachedImagedSizes, path);
  439. }
  440. catch (Exception ex)
  441. {
  442. _logger.ErrorException("Error saving image size file", ex);
  443. }
  444. }
  445. }
  446. private string ImageSizeFile
  447. {
  448. get
  449. {
  450. return Path.Combine(_appPaths.DataPath, "imagesizes.json");
  451. }
  452. }
  453. /// <summary>
  454. /// Gets the image cache tag.
  455. /// </summary>
  456. /// <param name="item">The item.</param>
  457. /// <param name="image">The image.</param>
  458. /// <returns>Guid.</returns>
  459. /// <exception cref="System.ArgumentNullException">item</exception>
  460. public string GetImageCacheTag(IHasImages item, ItemImageInfo image)
  461. {
  462. if (item == null)
  463. {
  464. throw new ArgumentNullException("item");
  465. }
  466. if (image == null)
  467. {
  468. throw new ArgumentNullException("image");
  469. }
  470. var supportedEnhancers = GetSupportedEnhancers(item, image.Type);
  471. return GetImageCacheTag(item, image, supportedEnhancers.ToList());
  472. }
  473. /// <summary>
  474. /// Gets the image cache tag.
  475. /// </summary>
  476. /// <param name="item">The item.</param>
  477. /// <param name="image">The image.</param>
  478. /// <param name="imageEnhancers">The image enhancers.</param>
  479. /// <returns>Guid.</returns>
  480. /// <exception cref="System.ArgumentNullException">item</exception>
  481. public string GetImageCacheTag(IHasImages item, ItemImageInfo image, List<IImageEnhancer> imageEnhancers)
  482. {
  483. if (item == null)
  484. {
  485. throw new ArgumentNullException("item");
  486. }
  487. if (imageEnhancers == null)
  488. {
  489. throw new ArgumentNullException("imageEnhancers");
  490. }
  491. if (image == null)
  492. {
  493. throw new ArgumentNullException("image");
  494. }
  495. var originalImagePath = image.Path;
  496. var dateModified = image.DateModified;
  497. var imageType = image.Type;
  498. // Optimization
  499. if (imageEnhancers.Count == 0)
  500. {
  501. return (originalImagePath + dateModified.Ticks).GetMD5().ToString("N");
  502. }
  503. // Cache name is created with supported enhancers combined with the last config change so we pick up new config changes
  504. var cacheKeys = imageEnhancers.Select(i => i.GetConfigurationCacheKey(item, imageType)).ToList();
  505. cacheKeys.Add(originalImagePath + dateModified.Ticks);
  506. return string.Join("|", cacheKeys.ToArray()).GetMD5().ToString("N");
  507. }
  508. /// <summary>
  509. /// Gets the enhanced image.
  510. /// </summary>
  511. /// <param name="item">The item.</param>
  512. /// <param name="imageType">Type of the image.</param>
  513. /// <param name="imageIndex">Index of the image.</param>
  514. /// <returns>Task{System.String}.</returns>
  515. public async Task<string> GetEnhancedImage(IHasImages item, ImageType imageType, int imageIndex)
  516. {
  517. var enhancers = GetSupportedEnhancers(item, imageType).ToList();
  518. var imageInfo = item.GetImageInfo(imageType, imageIndex);
  519. var result = await GetEnhancedImage(imageInfo, item, imageIndex, enhancers);
  520. return result.Item1;
  521. }
  522. private async Task<Tuple<string, DateTime>> GetEnhancedImage(ItemImageInfo image,
  523. IHasImages item,
  524. int imageIndex,
  525. List<IImageEnhancer> enhancers)
  526. {
  527. var originalImagePath = image.Path;
  528. var dateModified = image.DateModified;
  529. var imageType = image.Type;
  530. try
  531. {
  532. var cacheGuid = GetImageCacheTag(item, image, enhancers);
  533. // Enhance if we have enhancers
  534. var ehnancedImagePath = await GetEnhancedImageInternal(originalImagePath, item, imageType, imageIndex, enhancers, cacheGuid).ConfigureAwait(false);
  535. // If the path changed update dateModified
  536. if (!ehnancedImagePath.Equals(originalImagePath, StringComparison.OrdinalIgnoreCase))
  537. {
  538. dateModified = _fileSystem.GetLastWriteTimeUtc(ehnancedImagePath);
  539. return new Tuple<string, DateTime>(ehnancedImagePath, dateModified);
  540. }
  541. }
  542. catch (Exception ex)
  543. {
  544. _logger.Error("Error enhancing image", ex);
  545. }
  546. return new Tuple<string, DateTime>(originalImagePath, dateModified);
  547. }
  548. /// <summary>
  549. /// Gets the enhanced image internal.
  550. /// </summary>
  551. /// <param name="originalImagePath">The original image path.</param>
  552. /// <param name="item">The item.</param>
  553. /// <param name="imageType">Type of the image.</param>
  554. /// <param name="imageIndex">Index of the image.</param>
  555. /// <param name="supportedEnhancers">The supported enhancers.</param>
  556. /// <param name="cacheGuid">The cache unique identifier.</param>
  557. /// <returns>Task&lt;System.String&gt;.</returns>
  558. /// <exception cref="ArgumentNullException">
  559. /// originalImagePath
  560. /// or
  561. /// item
  562. /// </exception>
  563. private async Task<string> GetEnhancedImageInternal(string originalImagePath,
  564. IHasImages item,
  565. ImageType imageType,
  566. int imageIndex,
  567. IEnumerable<IImageEnhancer> supportedEnhancers,
  568. string cacheGuid)
  569. {
  570. if (string.IsNullOrEmpty(originalImagePath))
  571. {
  572. throw new ArgumentNullException("originalImagePath");
  573. }
  574. if (item == null)
  575. {
  576. throw new ArgumentNullException("item");
  577. }
  578. // All enhanced images are saved as png to allow transparency
  579. var enhancedImagePath = GetCachePath(EnhancedImageCachePath, cacheGuid + ".png");
  580. var semaphore = GetLock(enhancedImagePath);
  581. await semaphore.WaitAsync().ConfigureAwait(false);
  582. // Check again in case of contention
  583. if (File.Exists(enhancedImagePath))
  584. {
  585. semaphore.Release();
  586. return enhancedImagePath;
  587. }
  588. try
  589. {
  590. Directory.CreateDirectory(Path.GetDirectoryName(enhancedImagePath));
  591. await ExecuteImageEnhancers(supportedEnhancers, originalImagePath, enhancedImagePath, item, imageType, imageIndex).ConfigureAwait(false);
  592. }
  593. finally
  594. {
  595. semaphore.Release();
  596. }
  597. return enhancedImagePath;
  598. }
  599. /// <summary>
  600. /// Executes the image enhancers.
  601. /// </summary>
  602. /// <param name="imageEnhancers">The image enhancers.</param>
  603. /// <param name="inputPath">The input path.</param>
  604. /// <param name="outputPath">The output path.</param>
  605. /// <param name="item">The item.</param>
  606. /// <param name="imageType">Type of the image.</param>
  607. /// <param name="imageIndex">Index of the image.</param>
  608. /// <returns>Task{EnhancedImage}.</returns>
  609. private async Task ExecuteImageEnhancers(IEnumerable<IImageEnhancer> imageEnhancers, string inputPath, string outputPath, IHasImages item, ImageType imageType, int imageIndex)
  610. {
  611. // Run the enhancers sequentially in order of priority
  612. foreach (var enhancer in imageEnhancers)
  613. {
  614. var typeName = enhancer.GetType().Name;
  615. try
  616. {
  617. await enhancer.EnhanceImageAsync(item, inputPath, outputPath, imageType, imageIndex).ConfigureAwait(false);
  618. }
  619. catch (Exception ex)
  620. {
  621. _logger.ErrorException("{0} failed enhancing {1}", ex, typeName, item.Name);
  622. throw;
  623. }
  624. // Feed the output into the next enhancer as input
  625. inputPath = outputPath;
  626. }
  627. }
  628. /// <summary>
  629. /// The _semaphoreLocks
  630. /// </summary>
  631. private readonly ConcurrentDictionary<string, SemaphoreSlim> _semaphoreLocks = new ConcurrentDictionary<string, SemaphoreSlim>();
  632. /// <summary>
  633. /// Gets the lock.
  634. /// </summary>
  635. /// <param name="filename">The filename.</param>
  636. /// <returns>System.Object.</returns>
  637. private SemaphoreSlim GetLock(string filename)
  638. {
  639. return _semaphoreLocks.GetOrAdd(filename, key => new SemaphoreSlim(1, 1));
  640. }
  641. /// <summary>
  642. /// Gets the cache path.
  643. /// </summary>
  644. /// <param name="path">The path.</param>
  645. /// <param name="uniqueName">Name of the unique.</param>
  646. /// <param name="fileExtension">The file extension.</param>
  647. /// <returns>System.String.</returns>
  648. /// <exception cref="System.ArgumentNullException">
  649. /// path
  650. /// or
  651. /// uniqueName
  652. /// or
  653. /// fileExtension
  654. /// </exception>
  655. public string GetCachePath(string path, string uniqueName, string fileExtension)
  656. {
  657. if (string.IsNullOrEmpty(path))
  658. {
  659. throw new ArgumentNullException("path");
  660. }
  661. if (string.IsNullOrEmpty(uniqueName))
  662. {
  663. throw new ArgumentNullException("uniqueName");
  664. }
  665. if (string.IsNullOrEmpty(fileExtension))
  666. {
  667. throw new ArgumentNullException("fileExtension");
  668. }
  669. var filename = uniqueName.GetMD5() + fileExtension;
  670. return GetCachePath(path, filename);
  671. }
  672. /// <summary>
  673. /// Gets the cache path.
  674. /// </summary>
  675. /// <param name="path">The path.</param>
  676. /// <param name="filename">The filename.</param>
  677. /// <returns>System.String.</returns>
  678. /// <exception cref="System.ArgumentNullException">
  679. /// path
  680. /// or
  681. /// filename
  682. /// </exception>
  683. public string GetCachePath(string path, string filename)
  684. {
  685. if (string.IsNullOrEmpty(path))
  686. {
  687. throw new ArgumentNullException("path");
  688. }
  689. if (string.IsNullOrEmpty(filename))
  690. {
  691. throw new ArgumentNullException("filename");
  692. }
  693. var prefix = filename.Substring(0, 1);
  694. path = Path.Combine(path, prefix);
  695. return Path.Combine(path, filename);
  696. }
  697. public IEnumerable<IImageEnhancer> GetSupportedEnhancers(IHasImages item, ImageType imageType)
  698. {
  699. return ImageEnhancers.Where(i =>
  700. {
  701. try
  702. {
  703. return i.Supports(item, imageType);
  704. }
  705. catch (Exception ex)
  706. {
  707. _logger.ErrorException("Error in image enhancer: {0}", ex, i.GetType().Name);
  708. return false;
  709. }
  710. });
  711. }
  712. private bool _disposed;
  713. public void Dispose()
  714. {
  715. _disposed = true;
  716. Wand.CloseEnvironment();
  717. _saveImageSizeTimer.Dispose();
  718. }
  719. private void CheckDisposed()
  720. {
  721. if (_disposed)
  722. {
  723. throw new ObjectDisposedException(GetType().Name);
  724. }
  725. }
  726. }
  727. }