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 = GetImageSize(originalImagePath, dateModified);
  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. // Grab the cache file if it already exists
  133. if (File.Exists(cacheFilePath))
  134. {
  135. using (var fileStream = new FileStream(cacheFilePath, FileMode.Open, FileAccess.Read, FileShare.Read, StreamDefaults.DefaultFileStreamBufferSize, FileOptions.Asynchronous))
  136. {
  137. await fileStream.CopyToAsync(toStream).ConfigureAwait(false);
  138. return;
  139. }
  140. }
  141. var semaphore = GetLock(cacheFilePath);
  142. await semaphore.WaitAsync().ConfigureAwait(false);
  143. // Check again in case of lock contention
  144. if (File.Exists(cacheFilePath))
  145. {
  146. try
  147. {
  148. using (var fileStream = new FileStream(cacheFilePath, FileMode.Open, FileAccess.Read, FileShare.Read, StreamDefaults.DefaultFileStreamBufferSize, FileOptions.Asynchronous))
  149. {
  150. await fileStream.CopyToAsync(toStream).ConfigureAwait(false);
  151. return;
  152. }
  153. }
  154. finally
  155. {
  156. semaphore.Release();
  157. }
  158. }
  159. try
  160. {
  161. using (var fileStream = File.OpenRead(originalImagePath))
  162. {
  163. using (var originalImage = Image.FromStream(fileStream, true, false))
  164. {
  165. var newWidth = Convert.ToInt32(newSize.Width);
  166. var newHeight = Convert.ToInt32(newSize.Height);
  167. // Graphics.FromImage will throw an exception if the PixelFormat is Indexed, so we need to handle that here
  168. var thumbnail = !ImageExtensions.IsPixelFormatSupportedByGraphicsObject(originalImage.PixelFormat) ? new Bitmap(originalImage, newWidth, newHeight) : new Bitmap(newWidth, newHeight, originalImage.PixelFormat);
  169. // Preserve the original resolution
  170. thumbnail.SetResolution(originalImage.HorizontalResolution, originalImage.VerticalResolution);
  171. var thumbnailGraph = Graphics.FromImage(thumbnail);
  172. thumbnailGraph.CompositingQuality = CompositingQuality.HighQuality;
  173. thumbnailGraph.SmoothingMode = SmoothingMode.HighQuality;
  174. thumbnailGraph.InterpolationMode = InterpolationMode.HighQualityBicubic;
  175. thumbnailGraph.PixelOffsetMode = PixelOffsetMode.HighQuality;
  176. thumbnailGraph.CompositingMode = CompositingMode.SourceOver;
  177. thumbnailGraph.DrawImage(originalImage, 0, 0, newWidth, newHeight);
  178. var outputFormat = originalImage.RawFormat;
  179. using (var memoryStream = new MemoryStream())
  180. {
  181. // Save to the memory stream
  182. thumbnail.Save(outputFormat, memoryStream, quality.Value);
  183. var bytes = memoryStream.ToArray();
  184. var outputTask = toStream.WriteAsync(bytes, 0, bytes.Length);
  185. // kick off a task to cache the result
  186. await CacheResizedImage(cacheFilePath, bytes).ConfigureAwait(false);
  187. await outputTask.ConfigureAwait(false);
  188. }
  189. thumbnailGraph.Dispose();
  190. thumbnail.Dispose();
  191. }
  192. }
  193. }
  194. finally
  195. {
  196. semaphore.Release();
  197. }
  198. }
  199. /// <summary>
  200. /// Caches the resized image.
  201. /// </summary>
  202. /// <param name="cacheFilePath">The cache file path.</param>
  203. /// <param name="bytes">The bytes.</param>
  204. private async Task CacheResizedImage(string cacheFilePath, byte[] bytes)
  205. {
  206. // Save to the cache location
  207. using (var cacheFileStream = new FileStream(cacheFilePath, FileMode.Create, FileAccess.Write, FileShare.Read, StreamDefaults.DefaultFileStreamBufferSize, FileOptions.Asynchronous))
  208. {
  209. // Save to the filestream
  210. await cacheFileStream.WriteAsync(bytes, 0, bytes.Length).ConfigureAwait(false);
  211. }
  212. }
  213. /// <summary>
  214. /// Gets the cache file path based on a set of parameters
  215. /// </summary>
  216. /// <param name="originalPath">The path to the original image file</param>
  217. /// <param name="outputSize">The size to output the image in</param>
  218. /// <param name="quality">Quality level, from 0-100. Currently only applies to JPG. The default value should suffice.</param>
  219. /// <param name="dateModified">The last modified date of the image</param>
  220. /// <returns>System.String.</returns>
  221. private string GetCacheFilePath(string originalPath, ImageSize outputSize, int quality, DateTime dateModified)
  222. {
  223. var filename = originalPath;
  224. filename += "width=" + outputSize.Width;
  225. filename += "height=" + outputSize.Height;
  226. filename += "quality=" + quality;
  227. filename += "datemodified=" + dateModified.Ticks;
  228. return ResizedImageCache.GetResourcePath(filename, Path.GetExtension(originalPath));
  229. }
  230. /// <summary>
  231. /// Gets image dimensions
  232. /// </summary>
  233. /// <param name="imagePath">The image path.</param>
  234. /// <param name="dateModified">The date modified.</param>
  235. /// <returns>Task{ImageSize}.</returns>
  236. /// <exception cref="System.ArgumentNullException">imagePath</exception>
  237. public ImageSize GetImageSize(string imagePath, DateTime dateModified)
  238. {
  239. if (string.IsNullOrEmpty(imagePath))
  240. {
  241. throw new ArgumentNullException("imagePath");
  242. }
  243. var name = imagePath + "datemodified=" + dateModified.Ticks;
  244. return _cachedImagedSizes.GetOrAdd(name, keyName => GetImageSize(keyName, imagePath));
  245. }
  246. protected readonly CultureInfo UsCulture = new CultureInfo("en-US");
  247. /// <summary>
  248. /// Gets the size of the image.
  249. /// </summary>
  250. /// <param name="keyName">Name of the key.</param>
  251. /// <param name="imagePath">The image path.</param>
  252. /// <returns>ImageSize.</returns>
  253. private ImageSize GetImageSize(string keyName, string imagePath)
  254. {
  255. // Now check the file system cache
  256. var fullCachePath = ImageSizeCache.GetResourcePath(keyName, ".txt");
  257. try
  258. {
  259. var result = File.ReadAllText(fullCachePath).Split('|').Select(i => double.Parse(i, UsCulture)).ToArray();
  260. return new ImageSize { Width = result[0], Height = result[1] };
  261. }
  262. catch (FileNotFoundException)
  263. {
  264. // Cache file doesn't exist no biggie
  265. }
  266. _logger.Debug("Getting image size for {0}", imagePath);
  267. var size = ImageHeader.GetDimensions(imagePath, _logger);
  268. // Update the file system cache
  269. File.WriteAllText(fullCachePath, size.Width.ToString(UsCulture) + @"|" + size.Height.ToString(UsCulture));
  270. return new ImageSize { Width = size.Width, Height = size.Height };
  271. }
  272. /// <summary>
  273. /// Gets the image path.
  274. /// </summary>
  275. /// <param name="item">The item.</param>
  276. /// <param name="imageType">Type of the image.</param>
  277. /// <param name="imageIndex">Index of the image.</param>
  278. /// <returns>System.String.</returns>
  279. /// <exception cref="System.ArgumentNullException">item</exception>
  280. /// <exception cref="System.InvalidOperationException"></exception>
  281. public string GetImagePath(BaseItem item, ImageType imageType, int imageIndex)
  282. {
  283. if (item == null)
  284. {
  285. throw new ArgumentNullException("item");
  286. }
  287. if (imageType == ImageType.Backdrop)
  288. {
  289. if (item.BackdropImagePaths == null)
  290. {
  291. throw new InvalidOperationException(string.Format("Item {0} does not have any Backdrops.", item.Name));
  292. }
  293. return item.BackdropImagePaths[imageIndex];
  294. }
  295. if (imageType == ImageType.Screenshot)
  296. {
  297. if (item.ScreenshotImagePaths == null)
  298. {
  299. throw new InvalidOperationException(string.Format("Item {0} does not have any Screenshots.", item.Name));
  300. }
  301. return item.ScreenshotImagePaths[imageIndex];
  302. }
  303. if (imageType == ImageType.Chapter)
  304. {
  305. var video = (Video)item;
  306. if (video.Chapters == null)
  307. {
  308. throw new InvalidOperationException(string.Format("Item {0} does not have any Chapters.", item.Name));
  309. }
  310. return video.Chapters[imageIndex].ImagePath;
  311. }
  312. return item.GetImage(imageType);
  313. }
  314. /// <summary>
  315. /// Gets the image date modified.
  316. /// </summary>
  317. /// <param name="item">The item.</param>
  318. /// <param name="imageType">Type of the image.</param>
  319. /// <param name="imageIndex">Index of the image.</param>
  320. /// <returns>DateTime.</returns>
  321. /// <exception cref="System.ArgumentNullException">item</exception>
  322. public DateTime GetImageDateModified(BaseItem item, ImageType imageType, int imageIndex)
  323. {
  324. if (item == null)
  325. {
  326. throw new ArgumentNullException("item");
  327. }
  328. var imagePath = GetImagePath(item, imageType, imageIndex);
  329. return GetImageDateModified(item, imagePath);
  330. }
  331. /// <summary>
  332. /// Gets the image date modified.
  333. /// </summary>
  334. /// <param name="item">The item.</param>
  335. /// <param name="imagePath">The image path.</param>
  336. /// <returns>DateTime.</returns>
  337. /// <exception cref="System.ArgumentNullException">item</exception>
  338. public DateTime GetImageDateModified(BaseItem item, string imagePath)
  339. {
  340. if (item == null)
  341. {
  342. throw new ArgumentNullException("item");
  343. }
  344. if (string.IsNullOrEmpty(imagePath))
  345. {
  346. throw new ArgumentNullException("imagePath");
  347. }
  348. var metaFileEntry = item.ResolveArgs.GetMetaFileByPath(imagePath);
  349. // If we didn't the metafile entry, check the Season
  350. if (!metaFileEntry.HasValue)
  351. {
  352. var episode = item as Episode;
  353. if (episode != null && episode.Season != null)
  354. {
  355. episode.Season.ResolveArgs.GetMetaFileByPath(imagePath);
  356. }
  357. }
  358. // See if we can avoid a file system lookup by looking for the file in ResolveArgs
  359. return metaFileEntry == null ? File.GetLastWriteTimeUtc(imagePath) : metaFileEntry.Value.LastWriteTimeUtc;
  360. }
  361. /// <summary>
  362. /// Crops whitespace from an image, caches the result, and returns the cached path
  363. /// </summary>
  364. /// <param name="originalImagePath">The original image path.</param>
  365. /// <param name="dateModified">The date modified.</param>
  366. /// <returns>System.String.</returns>
  367. private async Task<string> GetCroppedImage(string originalImagePath, DateTime dateModified)
  368. {
  369. var name = originalImagePath;
  370. name += "datemodified=" + dateModified.Ticks;
  371. var croppedImagePath = CroppedImageCache.GetResourcePath(name, Path.GetExtension(originalImagePath));
  372. if (CroppedImageCache.ContainsFilePath(croppedImagePath))
  373. {
  374. return croppedImagePath;
  375. }
  376. var semaphore = GetLock(croppedImagePath);
  377. await semaphore.WaitAsync().ConfigureAwait(false);
  378. // Check again in case of contention
  379. if (CroppedImageCache.ContainsFilePath(croppedImagePath))
  380. {
  381. semaphore.Release();
  382. return croppedImagePath;
  383. }
  384. try
  385. {
  386. using (var fileStream = File.OpenRead(originalImagePath))
  387. {
  388. using (var originalImage = (Bitmap)Image.FromStream(fileStream, true, false))
  389. {
  390. var outputFormat = originalImage.RawFormat;
  391. using (var croppedImage = originalImage.CropWhitespace())
  392. {
  393. using (var outputStream = new FileStream(croppedImagePath, FileMode.Create, FileAccess.Write, FileShare.Read))
  394. {
  395. croppedImage.Save(outputFormat, outputStream, 100);
  396. }
  397. }
  398. }
  399. }
  400. }
  401. catch (Exception ex)
  402. {
  403. // We have to have a catch-all here because some of the .net image methods throw a plain old Exception
  404. _logger.ErrorException("Error cropping image {0}", ex, originalImagePath);
  405. return originalImagePath;
  406. }
  407. finally
  408. {
  409. semaphore.Release();
  410. }
  411. return croppedImagePath;
  412. }
  413. /// <summary>
  414. /// Runs an image through the image enhancers, caches the result, and returns the cached path
  415. /// </summary>
  416. /// <param name="originalImagePath">The original image path.</param>
  417. /// <param name="dateModified">The date modified of the original image file.</param>
  418. /// <param name="item">The item.</param>
  419. /// <param name="imageType">Type of the image.</param>
  420. /// <param name="imageIndex">Index of the image.</param>
  421. /// <returns>System.String.</returns>
  422. /// <exception cref="System.ArgumentNullException">originalImagePath</exception>
  423. public async Task<string> GetEnhancedImage(string originalImagePath, DateTime dateModified, BaseItem item, ImageType imageType, int imageIndex)
  424. {
  425. if (string.IsNullOrEmpty(originalImagePath))
  426. {
  427. throw new ArgumentNullException("originalImagePath");
  428. }
  429. if (item == null)
  430. {
  431. throw new ArgumentNullException("item");
  432. }
  433. var supportedEnhancers = _kernel.ImageEnhancers.Where(i => i.Supports(item, imageType)).ToList();
  434. // No enhancement - don't cache
  435. if (supportedEnhancers.Count == 0)
  436. {
  437. return originalImagePath;
  438. }
  439. var cacheGuid = GetImageCacheTag(originalImagePath, dateModified, supportedEnhancers, item, imageType);
  440. // All enhanced images are saved as png to allow transparency
  441. var enhancedImagePath = EnhancedImageCache.GetResourcePath(cacheGuid + ".png");
  442. if (EnhancedImageCache.ContainsFilePath(enhancedImagePath))
  443. {
  444. return enhancedImagePath;
  445. }
  446. var semaphore = GetLock(enhancedImagePath);
  447. await semaphore.WaitAsync().ConfigureAwait(false);
  448. // Check again in case of contention
  449. if (EnhancedImageCache.ContainsFilePath(enhancedImagePath))
  450. {
  451. semaphore.Release();
  452. return enhancedImagePath;
  453. }
  454. try
  455. {
  456. using (var fileStream = File.OpenRead(originalImagePath))
  457. {
  458. using (var originalImage = Image.FromStream(fileStream, true, false))
  459. {
  460. //Pass the image through registered enhancers
  461. using (var newImage = await ExecuteImageEnhancers(supportedEnhancers, originalImage, item, imageType, imageIndex).ConfigureAwait(false))
  462. {
  463. //And then save it in the cache
  464. using (var outputStream = new FileStream(enhancedImagePath, FileMode.Create, FileAccess.Write, FileShare.Read))
  465. {
  466. newImage.Save(ImageFormat.Png, outputStream, 100);
  467. }
  468. }
  469. }
  470. }
  471. }
  472. finally
  473. {
  474. semaphore.Release();
  475. }
  476. return enhancedImagePath;
  477. }
  478. /// <summary>
  479. /// Gets the image cache tag.
  480. /// </summary>
  481. /// <param name="item">The item.</param>
  482. /// <param name="imageType">Type of the image.</param>
  483. /// <param name="imagePath">The image path.</param>
  484. /// <returns>Guid.</returns>
  485. /// <exception cref="System.ArgumentNullException">item</exception>
  486. public Guid GetImageCacheTag(BaseItem item, ImageType imageType, string imagePath)
  487. {
  488. if (item == null)
  489. {
  490. throw new ArgumentNullException("item");
  491. }
  492. if (string.IsNullOrEmpty(imagePath))
  493. {
  494. throw new ArgumentNullException("imagePath");
  495. }
  496. var dateModified = GetImageDateModified(item, imagePath);
  497. var supportedEnhancers = _kernel.ImageEnhancers.Where(i => i.Supports(item, imageType));
  498. return GetImageCacheTag(imagePath, dateModified, supportedEnhancers, item, imageType);
  499. }
  500. /// <summary>
  501. /// Gets the image cache tag.
  502. /// </summary>
  503. /// <param name="originalImagePath">The original image path.</param>
  504. /// <param name="dateModified">The date modified of the original image file.</param>
  505. /// <param name="imageEnhancers">The image enhancers.</param>
  506. /// <param name="item">The item.</param>
  507. /// <param name="imageType">Type of the image.</param>
  508. /// <returns>Guid.</returns>
  509. /// <exception cref="System.ArgumentNullException">item</exception>
  510. public Guid GetImageCacheTag(string originalImagePath, DateTime dateModified, IEnumerable<IImageEnhancer> imageEnhancers, BaseItem item, ImageType imageType)
  511. {
  512. if (item == null)
  513. {
  514. throw new ArgumentNullException("item");
  515. }
  516. if (imageEnhancers == null)
  517. {
  518. throw new ArgumentNullException("imageEnhancers");
  519. }
  520. if (string.IsNullOrEmpty(originalImagePath))
  521. {
  522. throw new ArgumentNullException("originalImagePath");
  523. }
  524. // Cache name is created with supported enhancers combined with the last config change so we pick up new config changes
  525. var cacheKeys = imageEnhancers.Select(i => i.GetType().Name + i.LastConfigurationChange(item, imageType).Ticks).ToList();
  526. cacheKeys.Add(originalImagePath + dateModified.Ticks);
  527. return string.Join("|", cacheKeys.ToArray()).GetMD5();
  528. }
  529. /// <summary>
  530. /// Executes the image enhancers.
  531. /// </summary>
  532. /// <param name="imageEnhancers">The image enhancers.</param>
  533. /// <param name="originalImage">The original image.</param>
  534. /// <param name="item">The item.</param>
  535. /// <param name="imageType">Type of the image.</param>
  536. /// <param name="imageIndex">Index of the image.</param>
  537. /// <returns>Task{EnhancedImage}.</returns>
  538. private async Task<Image> ExecuteImageEnhancers(IEnumerable<IImageEnhancer> imageEnhancers, Image originalImage, BaseItem item, ImageType imageType, int imageIndex)
  539. {
  540. var result = originalImage;
  541. // Run the enhancers sequentially in order of priority
  542. foreach (var enhancer in imageEnhancers)
  543. {
  544. var typeName = enhancer.GetType().Name;
  545. _logger.Debug("Running {0} for {1}", typeName, item.Path ?? item.Name ?? "--Unknown--");
  546. try
  547. {
  548. result = await enhancer.EnhanceImageAsync(item, result, imageType, imageIndex).ConfigureAwait(false);
  549. }
  550. catch (Exception ex)
  551. {
  552. _logger.ErrorException("{0} failed enhancing {1}", ex, typeName, item.Name);
  553. throw;
  554. }
  555. }
  556. return result;
  557. }
  558. /// <summary>
  559. /// Gets the lock.
  560. /// </summary>
  561. /// <param name="filename">The filename.</param>
  562. /// <returns>System.Object.</returns>
  563. private SemaphoreSlim GetLock(string filename)
  564. {
  565. return _locks.GetOrAdd(filename, key => new SemaphoreSlim(1, 1));
  566. }
  567. }
  568. }