ImageManager.cs 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680
  1. using MediaBrowser.Common.Extensions;
  2. using MediaBrowser.Common.IO;
  3. using MediaBrowser.Controller.Entities;
  4. using MediaBrowser.Controller.Entities.TV;
  5. using MediaBrowser.Controller.Providers;
  6. using MediaBrowser.Model.Drawing;
  7. using MediaBrowser.Model.Entities;
  8. using MediaBrowser.Model.Logging;
  9. using System;
  10. using System.Collections.Concurrent;
  11. using System.Collections.Generic;
  12. using System.Drawing;
  13. using System.Drawing.Drawing2D;
  14. using System.Drawing.Imaging;
  15. using System.Globalization;
  16. using System.IO;
  17. using System.Linq;
  18. using System.Threading;
  19. using System.Threading.Tasks;
  20. namespace MediaBrowser.Controller.Drawing
  21. {
  22. /// <summary>
  23. /// Class ImageManager
  24. /// </summary>
  25. public class ImageManager
  26. {
  27. /// <summary>
  28. /// Gets the image size cache.
  29. /// </summary>
  30. /// <value>The image size cache.</value>
  31. private FileSystemRepository ImageSizeCache { get; set; }
  32. /// <summary>
  33. /// Gets or sets the resized image cache.
  34. /// </summary>
  35. /// <value>The resized image cache.</value>
  36. private FileSystemRepository ResizedImageCache { get; set; }
  37. /// <summary>
  38. /// Gets the cropped image cache.
  39. /// </summary>
  40. /// <value>The cropped image cache.</value>
  41. private FileSystemRepository CroppedImageCache { get; set; }
  42. /// <summary>
  43. /// Gets the cropped image cache.
  44. /// </summary>
  45. /// <value>The cropped image cache.</value>
  46. private FileSystemRepository EnhancedImageCache { get; set; }
  47. /// <summary>
  48. /// The cached imaged sizes
  49. /// </summary>
  50. private readonly ConcurrentDictionary<string, ImageSize> _cachedImagedSizes = new ConcurrentDictionary<string, ImageSize>();
  51. /// <summary>
  52. /// The _logger
  53. /// </summary>
  54. private readonly ILogger _logger;
  55. /// <summary>
  56. /// The _kernel
  57. /// </summary>
  58. private readonly Kernel _kernel;
  59. /// <summary>
  60. /// The _locks
  61. /// </summary>
  62. private readonly ConcurrentDictionary<string, SemaphoreSlim> _locks = new ConcurrentDictionary<string, SemaphoreSlim>();
  63. /// <summary>
  64. /// Initializes a new instance of the <see cref="ImageManager" /> class.
  65. /// </summary>
  66. /// <param name="kernel">The kernel.</param>
  67. /// <param name="logger">The logger.</param>
  68. /// <param name="appPaths">The app paths.</param>
  69. public ImageManager(Kernel kernel, ILogger logger, IServerApplicationPaths appPaths)
  70. {
  71. _logger = logger;
  72. _kernel = kernel;
  73. ImageSizeCache = new FileSystemRepository(Path.Combine(appPaths.ImageCachePath, "image-sizes"));
  74. ResizedImageCache = new FileSystemRepository(Path.Combine(appPaths.ImageCachePath, "resized-images"));
  75. CroppedImageCache = new FileSystemRepository(Path.Combine(appPaths.ImageCachePath, "cropped-images"));
  76. EnhancedImageCache = new FileSystemRepository(Path.Combine(appPaths.ImageCachePath, "enhanced-images"));
  77. }
  78. /// <summary>
  79. /// Processes an image by resizing to target dimensions
  80. /// </summary>
  81. /// <param name="entity">The entity that owns the image</param>
  82. /// <param name="imageType">The image type</param>
  83. /// <param name="imageIndex">The image index (currently only used with backdrops)</param>
  84. /// <param name="cropWhitespace">if set to <c>true</c> [crop whitespace].</param>
  85. /// <param name="dateModified">The last date modified of the original image file</param>
  86. /// <param name="toStream">The stream to save the new image to</param>
  87. /// <param name="width">Use if a fixed width is required. Aspect ratio will be preserved.</param>
  88. /// <param name="height">Use if a fixed height is required. Aspect ratio will be preserved.</param>
  89. /// <param name="maxWidth">Use if a max width is required. Aspect ratio will be preserved.</param>
  90. /// <param name="maxHeight">Use if a max height is required. Aspect ratio will be preserved.</param>
  91. /// <param name="quality">Quality level, from 0-100. Currently only applies to JPG. The default value should suffice.</param>
  92. /// <returns>Task.</returns>
  93. /// <exception cref="System.ArgumentNullException">entity</exception>
  94. public async Task ProcessImage(BaseItem entity, ImageType imageType, int imageIndex, bool cropWhitespace, DateTime dateModified, Stream toStream, int? width, int? height, int? maxWidth, int? maxHeight, int? quality)
  95. {
  96. if (entity == null)
  97. {
  98. throw new ArgumentNullException("entity");
  99. }
  100. if (toStream == null)
  101. {
  102. throw new ArgumentNullException("toStream");
  103. }
  104. var originalImagePath = GetImagePath(entity, imageType, imageIndex);
  105. if (cropWhitespace)
  106. {
  107. originalImagePath = await GetCroppedImage(originalImagePath, dateModified).ConfigureAwait(false);
  108. }
  109. try
  110. {
  111. // Enhance if we have enhancers
  112. var ehnancedImagePath = await GetEnhancedImage(originalImagePath, dateModified, entity, imageType, imageIndex).ConfigureAwait(false);
  113. // If the path changed update dateModified
  114. if (!ehnancedImagePath.Equals(originalImagePath, StringComparison.OrdinalIgnoreCase))
  115. {
  116. dateModified = File.GetLastWriteTimeUtc(ehnancedImagePath);
  117. originalImagePath = ehnancedImagePath;
  118. }
  119. }
  120. catch (Exception ex)
  121. {
  122. _logger.Error("Error enhancing image", ex);
  123. }
  124. var originalImageSize = await GetImageSize(originalImagePath, dateModified).ConfigureAwait(false);
  125. // Determine the output size based on incoming parameters
  126. var newSize = DrawingUtils.Resize(originalImageSize, width, height, maxWidth, maxHeight);
  127. if (!quality.HasValue)
  128. {
  129. quality = 90;
  130. }
  131. var cacheFilePath = GetCacheFilePath(originalImagePath, newSize, quality.Value, dateModified);
  132. var semaphore = GetLock(cacheFilePath);
  133. await semaphore.WaitAsync().ConfigureAwait(false);
  134. // Check again in case of lock contention
  135. if (File.Exists(cacheFilePath))
  136. {
  137. try
  138. {
  139. using (var fileStream = new FileStream(cacheFilePath, FileMode.Open, FileAccess.Read, FileShare.Read, StreamDefaults.DefaultFileStreamBufferSize, FileOptions.Asynchronous))
  140. {
  141. await fileStream.CopyToAsync(toStream).ConfigureAwait(false);
  142. return;
  143. }
  144. }
  145. finally
  146. {
  147. semaphore.Release();
  148. }
  149. }
  150. try
  151. {
  152. using (var fileStream = File.OpenRead(originalImagePath))
  153. {
  154. using (var originalImage = Image.FromStream(fileStream, true, false))
  155. {
  156. var newWidth = Convert.ToInt32(newSize.Width);
  157. var newHeight = Convert.ToInt32(newSize.Height);
  158. // Graphics.FromImage will throw an exception if the PixelFormat is Indexed, so we need to handle that here
  159. var thumbnail = !ImageExtensions.IsPixelFormatSupportedByGraphicsObject(originalImage.PixelFormat) ? new Bitmap(originalImage, newWidth, newHeight) : new Bitmap(newWidth, newHeight, originalImage.PixelFormat);
  160. // Preserve the original resolution
  161. thumbnail.SetResolution(originalImage.HorizontalResolution, originalImage.VerticalResolution);
  162. var thumbnailGraph = Graphics.FromImage(thumbnail);
  163. thumbnailGraph.CompositingQuality = CompositingQuality.HighQuality;
  164. thumbnailGraph.SmoothingMode = SmoothingMode.HighQuality;
  165. thumbnailGraph.InterpolationMode = InterpolationMode.HighQualityBicubic;
  166. thumbnailGraph.PixelOffsetMode = PixelOffsetMode.HighQuality;
  167. thumbnailGraph.CompositingMode = CompositingMode.SourceOver;
  168. thumbnailGraph.DrawImage(originalImage, 0, 0, newWidth, newHeight);
  169. var outputFormat = originalImage.RawFormat;
  170. using (var memoryStream = new MemoryStream())
  171. {
  172. // Save to the memory stream
  173. thumbnail.Save(outputFormat, memoryStream, quality.Value);
  174. var bytes = memoryStream.ToArray();
  175. var outputTask = toStream.WriteAsync(bytes, 0, bytes.Length);
  176. // kick off a task to cache the result
  177. await CacheResizedImage(cacheFilePath, bytes).ConfigureAwait(false);
  178. await outputTask.ConfigureAwait(false);
  179. }
  180. thumbnailGraph.Dispose();
  181. thumbnail.Dispose();
  182. }
  183. }
  184. }
  185. finally
  186. {
  187. semaphore.Release();
  188. }
  189. }
  190. /// <summary>
  191. /// Caches the resized image.
  192. /// </summary>
  193. /// <param name="cacheFilePath">The cache file path.</param>
  194. /// <param name="bytes">The bytes.</param>
  195. private async Task CacheResizedImage(string cacheFilePath, byte[] bytes)
  196. {
  197. // Save to the cache location
  198. using (var cacheFileStream = new FileStream(cacheFilePath, FileMode.Create, FileAccess.Write, FileShare.Read, StreamDefaults.DefaultFileStreamBufferSize, FileOptions.Asynchronous))
  199. {
  200. // Save to the filestream
  201. await cacheFileStream.WriteAsync(bytes, 0, bytes.Length).ConfigureAwait(false);
  202. }
  203. }
  204. /// <summary>
  205. /// Gets the cache file path based on a set of parameters
  206. /// </summary>
  207. /// <param name="originalPath">The path to the original image file</param>
  208. /// <param name="outputSize">The size to output the image in</param>
  209. /// <param name="quality">Quality level, from 0-100. Currently only applies to JPG. The default value should suffice.</param>
  210. /// <param name="dateModified">The last modified date of the image</param>
  211. /// <returns>System.String.</returns>
  212. private string GetCacheFilePath(string originalPath, ImageSize outputSize, int quality, DateTime dateModified)
  213. {
  214. var filename = originalPath;
  215. filename += "width=" + outputSize.Width;
  216. filename += "height=" + outputSize.Height;
  217. filename += "quality=" + quality;
  218. filename += "datemodified=" + dateModified.Ticks;
  219. return ResizedImageCache.GetResourcePath(filename, Path.GetExtension(originalPath));
  220. }
  221. /// <summary>
  222. /// Gets image dimensions
  223. /// </summary>
  224. /// <param name="imagePath">The image path.</param>
  225. /// <param name="dateModified">The date modified.</param>
  226. /// <returns>Task{ImageSize}.</returns>
  227. /// <exception cref="System.ArgumentNullException">imagePath</exception>
  228. public async Task<ImageSize> GetImageSize(string imagePath, DateTime dateModified)
  229. {
  230. if (string.IsNullOrEmpty(imagePath))
  231. {
  232. throw new ArgumentNullException("imagePath");
  233. }
  234. var name = imagePath + "datemodified=" + dateModified.Ticks;
  235. ImageSize size;
  236. if (!_cachedImagedSizes.TryGetValue(name, out size))
  237. {
  238. size = await GetImageSize(name, imagePath).ConfigureAwait(false);
  239. _cachedImagedSizes.AddOrUpdate(name, size, (keyName, oldValue) => size);
  240. }
  241. return size;
  242. }
  243. protected readonly CultureInfo UsCulture = new CultureInfo("en-US");
  244. /// <summary>
  245. /// Gets the size of the image.
  246. /// </summary>
  247. /// <param name="keyName">Name of the key.</param>
  248. /// <param name="imagePath">The image path.</param>
  249. /// <returns>ImageSize.</returns>
  250. private async Task<ImageSize> GetImageSize(string keyName, string imagePath)
  251. {
  252. // Now check the file system cache
  253. var fullCachePath = ImageSizeCache.GetResourcePath(keyName, ".txt");
  254. var semaphore = GetLock(fullCachePath);
  255. await semaphore.WaitAsync().ConfigureAwait(false);
  256. try
  257. {
  258. try
  259. {
  260. var result = File.ReadAllText(fullCachePath).Split('|').Select(i => double.Parse(i, UsCulture)).ToArray();
  261. return new ImageSize { Width = result[0], Height = result[1] };
  262. }
  263. catch (FileNotFoundException)
  264. {
  265. // Cache file doesn't exist no biggie
  266. }
  267. _logger.Debug("Getting image size for {0}", imagePath);
  268. var size = ImageHeader.GetDimensions(imagePath, _logger);
  269. // Update the file system cache
  270. File.WriteAllText(fullCachePath, size.Width.ToString(UsCulture) + @"|" + size.Height.ToString(UsCulture));
  271. return new ImageSize { Width = size.Width, Height = size.Height };
  272. }
  273. finally
  274. {
  275. semaphore.Release();
  276. }
  277. }
  278. /// <summary>
  279. /// Gets the image path.
  280. /// </summary>
  281. /// <param name="item">The item.</param>
  282. /// <param name="imageType">Type of the image.</param>
  283. /// <param name="imageIndex">Index of the image.</param>
  284. /// <returns>System.String.</returns>
  285. /// <exception cref="System.ArgumentNullException">item</exception>
  286. /// <exception cref="System.InvalidOperationException"></exception>
  287. public string GetImagePath(BaseItem item, ImageType imageType, int imageIndex)
  288. {
  289. if (item == null)
  290. {
  291. throw new ArgumentNullException("item");
  292. }
  293. if (imageType == ImageType.Backdrop)
  294. {
  295. if (item.BackdropImagePaths == null)
  296. {
  297. throw new InvalidOperationException(string.Format("Item {0} does not have any Backdrops.", item.Name));
  298. }
  299. return item.BackdropImagePaths[imageIndex];
  300. }
  301. if (imageType == ImageType.Screenshot)
  302. {
  303. if (item.ScreenshotImagePaths == null)
  304. {
  305. throw new InvalidOperationException(string.Format("Item {0} does not have any Screenshots.", item.Name));
  306. }
  307. return item.ScreenshotImagePaths[imageIndex];
  308. }
  309. if (imageType == ImageType.Chapter)
  310. {
  311. var video = (Video)item;
  312. if (video.Chapters == null)
  313. {
  314. throw new InvalidOperationException(string.Format("Item {0} does not have any Chapters.", item.Name));
  315. }
  316. return video.Chapters[imageIndex].ImagePath;
  317. }
  318. return item.GetImage(imageType);
  319. }
  320. /// <summary>
  321. /// Gets the image date modified.
  322. /// </summary>
  323. /// <param name="item">The item.</param>
  324. /// <param name="imageType">Type of the image.</param>
  325. /// <param name="imageIndex">Index of the image.</param>
  326. /// <returns>DateTime.</returns>
  327. /// <exception cref="System.ArgumentNullException">item</exception>
  328. public DateTime GetImageDateModified(BaseItem item, ImageType imageType, int imageIndex)
  329. {
  330. if (item == null)
  331. {
  332. throw new ArgumentNullException("item");
  333. }
  334. var imagePath = GetImagePath(item, imageType, imageIndex);
  335. return GetImageDateModified(item, imagePath);
  336. }
  337. /// <summary>
  338. /// Gets the image date modified.
  339. /// </summary>
  340. /// <param name="item">The item.</param>
  341. /// <param name="imagePath">The image path.</param>
  342. /// <returns>DateTime.</returns>
  343. /// <exception cref="System.ArgumentNullException">item</exception>
  344. public DateTime GetImageDateModified(BaseItem item, string imagePath)
  345. {
  346. if (item == null)
  347. {
  348. throw new ArgumentNullException("item");
  349. }
  350. if (string.IsNullOrEmpty(imagePath))
  351. {
  352. throw new ArgumentNullException("imagePath");
  353. }
  354. var metaFileEntry = item.ResolveArgs.GetMetaFileByPath(imagePath);
  355. // If we didn't the metafile entry, check the Season
  356. if (!metaFileEntry.HasValue)
  357. {
  358. var episode = item as Episode;
  359. if (episode != null && episode.Season != null)
  360. {
  361. episode.Season.ResolveArgs.GetMetaFileByPath(imagePath);
  362. }
  363. }
  364. // See if we can avoid a file system lookup by looking for the file in ResolveArgs
  365. return metaFileEntry == null ? File.GetLastWriteTimeUtc(imagePath) : metaFileEntry.Value.LastWriteTimeUtc;
  366. }
  367. /// <summary>
  368. /// Crops whitespace from an image, caches the result, and returns the cached path
  369. /// </summary>
  370. /// <param name="originalImagePath">The original image path.</param>
  371. /// <param name="dateModified">The date modified.</param>
  372. /// <returns>System.String.</returns>
  373. private async Task<string> GetCroppedImage(string originalImagePath, DateTime dateModified)
  374. {
  375. var name = originalImagePath;
  376. name += "datemodified=" + dateModified.Ticks;
  377. var croppedImagePath = CroppedImageCache.GetResourcePath(name, Path.GetExtension(originalImagePath));
  378. var semaphore = GetLock(croppedImagePath);
  379. await semaphore.WaitAsync().ConfigureAwait(false);
  380. // Check again in case of contention
  381. if (CroppedImageCache.ContainsFilePath(croppedImagePath))
  382. {
  383. semaphore.Release();
  384. return croppedImagePath;
  385. }
  386. try
  387. {
  388. using (var fileStream = File.OpenRead(originalImagePath))
  389. {
  390. using (var originalImage = (Bitmap)Image.FromStream(fileStream, true, false))
  391. {
  392. var outputFormat = originalImage.RawFormat;
  393. using (var croppedImage = originalImage.CropWhitespace())
  394. {
  395. using (var outputStream = new FileStream(croppedImagePath, FileMode.Create, FileAccess.Write, FileShare.Read))
  396. {
  397. croppedImage.Save(outputFormat, outputStream, 100);
  398. }
  399. }
  400. }
  401. }
  402. }
  403. catch (Exception ex)
  404. {
  405. // We have to have a catch-all here because some of the .net image methods throw a plain old Exception
  406. _logger.ErrorException("Error cropping image {0}", ex, originalImagePath);
  407. return originalImagePath;
  408. }
  409. finally
  410. {
  411. semaphore.Release();
  412. }
  413. return croppedImagePath;
  414. }
  415. /// <summary>
  416. /// Runs an image through the image enhancers, caches the result, and returns the cached path
  417. /// </summary>
  418. /// <param name="originalImagePath">The original image path.</param>
  419. /// <param name="dateModified">The date modified of the original image file.</param>
  420. /// <param name="item">The item.</param>
  421. /// <param name="imageType">Type of the image.</param>
  422. /// <param name="imageIndex">Index of the image.</param>
  423. /// <returns>System.String.</returns>
  424. /// <exception cref="System.ArgumentNullException">originalImagePath</exception>
  425. public async Task<string> GetEnhancedImage(string originalImagePath, DateTime dateModified, BaseItem item, ImageType imageType, int imageIndex)
  426. {
  427. if (string.IsNullOrEmpty(originalImagePath))
  428. {
  429. throw new ArgumentNullException("originalImagePath");
  430. }
  431. if (item == null)
  432. {
  433. throw new ArgumentNullException("item");
  434. }
  435. var supportedEnhancers = _kernel.ImageEnhancers.Where(i => i.Supports(item, imageType)).ToList();
  436. // No enhancement - don't cache
  437. if (supportedEnhancers.Count == 0)
  438. {
  439. return originalImagePath;
  440. }
  441. var cacheGuid = GetImageCacheTag(originalImagePath, dateModified, supportedEnhancers, item, imageType);
  442. // All enhanced images are saved as png to allow transparency
  443. var enhancedImagePath = EnhancedImageCache.GetResourcePath(cacheGuid + ".png");
  444. var semaphore = GetLock(enhancedImagePath);
  445. await semaphore.WaitAsync().ConfigureAwait(false);
  446. // Check again in case of contention
  447. if (EnhancedImageCache.ContainsFilePath(enhancedImagePath))
  448. {
  449. semaphore.Release();
  450. return enhancedImagePath;
  451. }
  452. try
  453. {
  454. using (var fileStream = File.OpenRead(originalImagePath))
  455. {
  456. using (var originalImage = Image.FromStream(fileStream, true, false))
  457. {
  458. //Pass the image through registered enhancers
  459. using (var newImage = await ExecuteImageEnhancers(supportedEnhancers, originalImage, item, imageType, imageIndex).ConfigureAwait(false))
  460. {
  461. //And then save it in the cache
  462. using (var outputStream = new FileStream(enhancedImagePath, FileMode.Create, FileAccess.Write, FileShare.Read))
  463. {
  464. newImage.Save(ImageFormat.Png, outputStream, 100);
  465. }
  466. }
  467. }
  468. }
  469. }
  470. finally
  471. {
  472. semaphore.Release();
  473. }
  474. return enhancedImagePath;
  475. }
  476. /// <summary>
  477. /// Gets the image cache tag.
  478. /// </summary>
  479. /// <param name="item">The item.</param>
  480. /// <param name="imageType">Type of the image.</param>
  481. /// <param name="imagePath">The image path.</param>
  482. /// <returns>Guid.</returns>
  483. /// <exception cref="System.ArgumentNullException">item</exception>
  484. public Guid GetImageCacheTag(BaseItem item, ImageType imageType, string imagePath)
  485. {
  486. if (item == null)
  487. {
  488. throw new ArgumentNullException("item");
  489. }
  490. if (string.IsNullOrEmpty(imagePath))
  491. {
  492. throw new ArgumentNullException("imagePath");
  493. }
  494. var dateModified = GetImageDateModified(item, imagePath);
  495. var supportedEnhancers = _kernel.ImageEnhancers.Where(i => i.Supports(item, imageType));
  496. return GetImageCacheTag(imagePath, dateModified, supportedEnhancers, item, imageType);
  497. }
  498. /// <summary>
  499. /// Gets the image cache tag.
  500. /// </summary>
  501. /// <param name="originalImagePath">The original image path.</param>
  502. /// <param name="dateModified">The date modified of the original image file.</param>
  503. /// <param name="imageEnhancers">The image enhancers.</param>
  504. /// <param name="item">The item.</param>
  505. /// <param name="imageType">Type of the image.</param>
  506. /// <returns>Guid.</returns>
  507. /// <exception cref="System.ArgumentNullException">item</exception>
  508. public Guid GetImageCacheTag(string originalImagePath, DateTime dateModified, IEnumerable<IImageEnhancer> imageEnhancers, BaseItem item, ImageType imageType)
  509. {
  510. if (item == null)
  511. {
  512. throw new ArgumentNullException("item");
  513. }
  514. if (imageEnhancers == null)
  515. {
  516. throw new ArgumentNullException("imageEnhancers");
  517. }
  518. if (string.IsNullOrEmpty(originalImagePath))
  519. {
  520. throw new ArgumentNullException("originalImagePath");
  521. }
  522. // Cache name is created with supported enhancers combined with the last config change so we pick up new config changes
  523. var cacheKeys = imageEnhancers.Select(i => i.GetType().Name + i.LastConfigurationChange(item, imageType).Ticks).ToList();
  524. cacheKeys.Add(originalImagePath + dateModified.Ticks);
  525. return string.Join("|", cacheKeys.ToArray()).GetMD5();
  526. }
  527. /// <summary>
  528. /// Executes the image enhancers.
  529. /// </summary>
  530. /// <param name="imageEnhancers">The image enhancers.</param>
  531. /// <param name="originalImage">The original image.</param>
  532. /// <param name="item">The item.</param>
  533. /// <param name="imageType">Type of the image.</param>
  534. /// <param name="imageIndex">Index of the image.</param>
  535. /// <returns>Task{EnhancedImage}.</returns>
  536. private async Task<Image> ExecuteImageEnhancers(IEnumerable<IImageEnhancer> imageEnhancers, Image originalImage, BaseItem item, ImageType imageType, int imageIndex)
  537. {
  538. var result = originalImage;
  539. // Run the enhancers sequentially in order of priority
  540. foreach (var enhancer in imageEnhancers)
  541. {
  542. var typeName = enhancer.GetType().Name;
  543. _logger.Debug("Running {0} for {1}", typeName, item.Path ?? item.Name ?? "--Unknown--");
  544. try
  545. {
  546. result = await enhancer.EnhanceImageAsync(item, result, imageType, imageIndex).ConfigureAwait(false);
  547. }
  548. catch (Exception ex)
  549. {
  550. _logger.ErrorException("{0} failed enhancing {1}", ex, typeName, item.Name);
  551. throw;
  552. }
  553. }
  554. return result;
  555. }
  556. /// <summary>
  557. /// Gets the lock.
  558. /// </summary>
  559. /// <param name="filename">The filename.</param>
  560. /// <returns>System.Object.</returns>
  561. private SemaphoreSlim GetLock(string filename)
  562. {
  563. return _locks.GetOrAdd(filename, key => new SemaphoreSlim(1, 1));
  564. }
  565. }
  566. }