ImageManager.cs 28 KB

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