ImageManager.cs 28 KB

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