ImageManager.cs 29 KB

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