ImageProcessor.cs 30 KB

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