ImageManager.cs 27 KB

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