ImageManager.cs 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799
  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.Persistence;
  6. using MediaBrowser.Controller.Providers;
  7. using MediaBrowser.Model.Drawing;
  8. using MediaBrowser.Model.Entities;
  9. using MediaBrowser.Model.Logging;
  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.Globalization;
  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 list of currently registered image processors
  30. /// Image processors are specialized metadata providers that run after the normal ones
  31. /// </summary>
  32. /// <value>The image enhancers.</value>
  33. public IEnumerable<IImageEnhancer> ImageEnhancers { get; set; }
  34. /// <summary>
  35. /// Gets the image size cache.
  36. /// </summary>
  37. /// <value>The image size cache.</value>
  38. private FileSystemRepository ImageSizeCache { get; set; }
  39. /// <summary>
  40. /// Gets or sets the resized image cache.
  41. /// </summary>
  42. /// <value>The resized image cache.</value>
  43. private FileSystemRepository ResizedImageCache { get; set; }
  44. /// <summary>
  45. /// Gets the cropped image cache.
  46. /// </summary>
  47. /// <value>The cropped image cache.</value>
  48. private FileSystemRepository CroppedImageCache { get; set; }
  49. /// <summary>
  50. /// Gets the cropped image cache.
  51. /// </summary>
  52. /// <value>The cropped image cache.</value>
  53. private FileSystemRepository EnhancedImageCache { get; set; }
  54. /// <summary>
  55. /// The cached imaged sizes
  56. /// </summary>
  57. private readonly ConcurrentDictionary<string, ImageSize> _cachedImagedSizes = new ConcurrentDictionary<string, ImageSize>();
  58. /// <summary>
  59. /// The _logger
  60. /// </summary>
  61. private readonly ILogger _logger;
  62. private readonly IItemRepository _itemRepo;
  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="logger">The logger.</param>
  71. /// <param name="appPaths">The app paths.</param>
  72. /// <param name="itemRepo">The item repo.</param>
  73. public ImageManager(ILogger logger, IServerApplicationPaths appPaths, IItemRepository itemRepo)
  74. {
  75. _logger = logger;
  76. _itemRepo = itemRepo;
  77. ImageSizeCache = new FileSystemRepository(Path.Combine(appPaths.ImageCachePath, "image-sizes"));
  78. ResizedImageCache = new FileSystemRepository(Path.Combine(appPaths.ImageCachePath, "resized-images"));
  79. CroppedImageCache = new FileSystemRepository(Path.Combine(appPaths.ImageCachePath, "cropped-images"));
  80. EnhancedImageCache = new FileSystemRepository(Path.Combine(appPaths.ImageCachePath, "enhanced-images"));
  81. }
  82. /// <summary>
  83. /// Processes an image by resizing to target dimensions
  84. /// </summary>
  85. /// <param name="entity">The entity that owns the image</param>
  86. /// <param name="imageType">The image type</param>
  87. /// <param name="imageIndex">The image index (currently only used with backdrops)</param>
  88. /// <param name="originalImagePath">The original image path.</param>
  89. /// <param name="cropWhitespace">if set to <c>true</c> [crop whitespace].</param>
  90. /// <param name="dateModified">The last date modified of the original image file</param>
  91. /// <param name="toStream">The stream to save the new image to</param>
  92. /// <param name="width">Use if a fixed width is required. Aspect ratio will be preserved.</param>
  93. /// <param name="height">Use if a fixed height is required. Aspect ratio will be preserved.</param>
  94. /// <param name="maxWidth">Use if a max width is required. Aspect ratio will be preserved.</param>
  95. /// <param name="maxHeight">Use if a max height is required. Aspect ratio will be preserved.</param>
  96. /// <param name="quality">Quality level, from 0-100. Currently only applies to JPG. The default value should suffice.</param>
  97. /// <param name="enhancers">The enhancers.</param>
  98. /// <returns>Task.</returns>
  99. /// <exception cref="System.ArgumentNullException">entity</exception>
  100. public async Task ProcessImage(BaseItem entity, ImageType imageType, int imageIndex, string originalImagePath, bool cropWhitespace, DateTime dateModified, Stream toStream, int? width, int? height, int? maxWidth, int? maxHeight, int? quality, List<IImageEnhancer> enhancers)
  101. {
  102. if (entity == null)
  103. {
  104. throw new ArgumentNullException("entity");
  105. }
  106. if (toStream == null)
  107. {
  108. throw new ArgumentNullException("toStream");
  109. }
  110. if (cropWhitespace)
  111. {
  112. originalImagePath = await GetCroppedImage(originalImagePath, dateModified).ConfigureAwait(false);
  113. }
  114. // No enhancement - don't cache
  115. if (enhancers.Count > 0)
  116. {
  117. try
  118. {
  119. // Enhance if we have enhancers
  120. var ehnancedImagePath = await GetEnhancedImage(originalImagePath, dateModified, entity, imageType, imageIndex, enhancers).ConfigureAwait(false);
  121. // If the path changed update dateModified
  122. if (!ehnancedImagePath.Equals(originalImagePath, StringComparison.OrdinalIgnoreCase))
  123. {
  124. dateModified = File.GetLastWriteTimeUtc(ehnancedImagePath);
  125. originalImagePath = ehnancedImagePath;
  126. }
  127. }
  128. catch (Exception ex)
  129. {
  130. _logger.Error("Error enhancing image", ex);
  131. }
  132. }
  133. var originalImageSize = await GetImageSize(originalImagePath, dateModified).ConfigureAwait(false);
  134. // Determine the output size based on incoming parameters
  135. var newSize = DrawingUtils.Resize(originalImageSize, width, height, maxWidth, maxHeight);
  136. if (!quality.HasValue)
  137. {
  138. quality = 90;
  139. }
  140. var cacheFilePath = GetCacheFilePath(originalImagePath, newSize, quality.Value, dateModified);
  141. try
  142. {
  143. using (var fileStream = new FileStream(cacheFilePath, FileMode.Open, FileAccess.Read, FileShare.Read, StreamDefaults.DefaultFileStreamBufferSize, FileOptions.Asynchronous))
  144. {
  145. await fileStream.CopyToAsync(toStream).ConfigureAwait(false);
  146. return;
  147. }
  148. }
  149. catch (IOException)
  150. {
  151. // Cache file doesn't exist or is currently being written ro
  152. }
  153. var semaphore = GetLock(cacheFilePath);
  154. await semaphore.WaitAsync().ConfigureAwait(false);
  155. // Check again in case of lock contention
  156. if (File.Exists(cacheFilePath))
  157. {
  158. try
  159. {
  160. using (var fileStream = new FileStream(cacheFilePath, FileMode.Open, FileAccess.Read, FileShare.Read, StreamDefaults.DefaultFileStreamBufferSize, FileOptions.Asynchronous))
  161. {
  162. await fileStream.CopyToAsync(toStream).ConfigureAwait(false);
  163. return;
  164. }
  165. }
  166. finally
  167. {
  168. semaphore.Release();
  169. }
  170. }
  171. try
  172. {
  173. using (var fileStream = new FileStream(originalImagePath, FileMode.Open, FileAccess.Read, FileShare.Read, StreamDefaults.DefaultFileStreamBufferSize, true))
  174. {
  175. // Copy to memory stream to avoid Image locking file
  176. using (var memoryStream = new MemoryStream())
  177. {
  178. await fileStream.CopyToAsync(memoryStream).ConfigureAwait(false);
  179. using (var originalImage = Image.FromStream(memoryStream, true, false))
  180. {
  181. var newWidth = Convert.ToInt32(newSize.Width);
  182. var newHeight = Convert.ToInt32(newSize.Height);
  183. // Graphics.FromImage will throw an exception if the PixelFormat is Indexed, so we need to handle that here
  184. using (var thumbnail = !ImageExtensions.IsPixelFormatSupportedByGraphicsObject(originalImage.PixelFormat) ? new Bitmap(originalImage, newWidth, newHeight) : new Bitmap(newWidth, newHeight, originalImage.PixelFormat))
  185. {
  186. // Preserve the original resolution
  187. thumbnail.SetResolution(originalImage.HorizontalResolution, originalImage.VerticalResolution);
  188. using (var thumbnailGraph = Graphics.FromImage(thumbnail))
  189. {
  190. thumbnailGraph.CompositingQuality = CompositingQuality.HighQuality;
  191. thumbnailGraph.SmoothingMode = SmoothingMode.HighQuality;
  192. thumbnailGraph.InterpolationMode = InterpolationMode.HighQualityBicubic;
  193. thumbnailGraph.PixelOffsetMode = PixelOffsetMode.HighQuality;
  194. thumbnailGraph.CompositingMode = CompositingMode.SourceOver;
  195. thumbnailGraph.DrawImage(originalImage, 0, 0, newWidth, newHeight);
  196. var outputFormat = originalImage.RawFormat;
  197. using (var outputMemoryStream = new MemoryStream())
  198. {
  199. // Save to the memory stream
  200. thumbnail.Save(outputFormat, outputMemoryStream, quality.Value);
  201. var bytes = outputMemoryStream.ToArray();
  202. var outputTask = toStream.WriteAsync(bytes, 0, bytes.Length);
  203. // kick off a task to cache the result
  204. var cacheTask = CacheResizedImage(cacheFilePath, bytes);
  205. await Task.WhenAll(outputTask, cacheTask).ConfigureAwait(false);
  206. }
  207. }
  208. }
  209. }
  210. }
  211. }
  212. }
  213. finally
  214. {
  215. semaphore.Release();
  216. }
  217. }
  218. /// <summary>
  219. /// Caches the resized image.
  220. /// </summary>
  221. /// <param name="cacheFilePath">The cache file path.</param>
  222. /// <param name="bytes">The bytes.</param>
  223. private async Task CacheResizedImage(string cacheFilePath, byte[] bytes)
  224. {
  225. var parentPath = Path.GetDirectoryName(cacheFilePath);
  226. if (!Directory.Exists(parentPath))
  227. {
  228. Directory.CreateDirectory(parentPath);
  229. }
  230. // Save to the cache location
  231. using (var cacheFileStream = new FileStream(cacheFilePath, FileMode.Create, FileAccess.Write, FileShare.Read, StreamDefaults.DefaultFileStreamBufferSize, FileOptions.Asynchronous))
  232. {
  233. // Save to the filestream
  234. await cacheFileStream.WriteAsync(bytes, 0, bytes.Length).ConfigureAwait(false);
  235. }
  236. }
  237. /// <summary>
  238. /// Gets the cache file path based on a set of parameters
  239. /// </summary>
  240. /// <param name="originalPath">The path to the original image file</param>
  241. /// <param name="outputSize">The size to output the image in</param>
  242. /// <param name="quality">Quality level, from 0-100. Currently only applies to JPG. The default value should suffice.</param>
  243. /// <param name="dateModified">The last modified date of the image</param>
  244. /// <returns>System.String.</returns>
  245. private string GetCacheFilePath(string originalPath, ImageSize outputSize, int quality, DateTime dateModified)
  246. {
  247. var filename = originalPath;
  248. filename += "width=" + outputSize.Width;
  249. filename += "height=" + outputSize.Height;
  250. filename += "quality=" + quality;
  251. filename += "datemodified=" + dateModified.Ticks;
  252. return ResizedImageCache.GetResourcePath(filename, Path.GetExtension(originalPath));
  253. }
  254. /// <summary>
  255. /// Gets image dimensions
  256. /// </summary>
  257. /// <param name="imagePath">The image path.</param>
  258. /// <param name="dateModified">The date modified.</param>
  259. /// <returns>Task{ImageSize}.</returns>
  260. /// <exception cref="System.ArgumentNullException">imagePath</exception>
  261. public async Task<ImageSize> GetImageSize(string imagePath, DateTime dateModified)
  262. {
  263. if (string.IsNullOrEmpty(imagePath))
  264. {
  265. throw new ArgumentNullException("imagePath");
  266. }
  267. var name = imagePath + "datemodified=" + dateModified.Ticks;
  268. ImageSize size;
  269. if (!_cachedImagedSizes.TryGetValue(name, out size))
  270. {
  271. size = await GetImageSize(name, imagePath).ConfigureAwait(false);
  272. _cachedImagedSizes.AddOrUpdate(name, size, (keyName, oldValue) => size);
  273. }
  274. return size;
  275. }
  276. protected readonly CultureInfo UsCulture = new CultureInfo("en-US");
  277. /// <summary>
  278. /// Gets the size of the image.
  279. /// </summary>
  280. /// <param name="keyName">Name of the key.</param>
  281. /// <param name="imagePath">The image path.</param>
  282. /// <returns>ImageSize.</returns>
  283. private async Task<ImageSize> GetImageSize(string keyName, string imagePath)
  284. {
  285. // Now check the file system cache
  286. var fullCachePath = ImageSizeCache.GetResourcePath(keyName, ".txt");
  287. try
  288. {
  289. var result = File.ReadAllText(fullCachePath).Split('|').Select(i => double.Parse(i, UsCulture)).ToArray();
  290. return new ImageSize { Width = result[0], Height = result[1] };
  291. }
  292. catch (IOException)
  293. {
  294. // Cache file doesn't exist or is currently being written to
  295. }
  296. var semaphore = GetLock(fullCachePath);
  297. await semaphore.WaitAsync().ConfigureAwait(false);
  298. try
  299. {
  300. var result = File.ReadAllText(fullCachePath).Split('|').Select(i => double.Parse(i, UsCulture)).ToArray();
  301. return new ImageSize { Width = result[0], Height = result[1] };
  302. }
  303. catch (FileNotFoundException)
  304. {
  305. // Cache file doesn't exist no biggie
  306. }
  307. catch (DirectoryNotFoundException)
  308. {
  309. // Cache file doesn't exist no biggie
  310. }
  311. catch
  312. {
  313. semaphore.Release();
  314. throw;
  315. }
  316. try
  317. {
  318. var size = await ImageHeader.GetDimensions(imagePath, _logger).ConfigureAwait(false);
  319. var parentPath = Path.GetDirectoryName(fullCachePath);
  320. if (!Directory.Exists(parentPath))
  321. {
  322. Directory.CreateDirectory(parentPath);
  323. }
  324. // Update the file system cache
  325. File.WriteAllText(fullCachePath, size.Width.ToString(UsCulture) + @"|" + size.Height.ToString(UsCulture));
  326. return new ImageSize { Width = size.Width, Height = size.Height };
  327. }
  328. finally
  329. {
  330. semaphore.Release();
  331. }
  332. }
  333. /// <summary>
  334. /// Gets the image path.
  335. /// </summary>
  336. /// <param name="item">The item.</param>
  337. /// <param name="imageType">Type of the image.</param>
  338. /// <param name="imageIndex">Index of the image.</param>
  339. /// <returns>System.String.</returns>
  340. /// <exception cref="System.ArgumentNullException">item</exception>
  341. /// <exception cref="System.InvalidOperationException"></exception>
  342. public string GetImagePath(BaseItem item, ImageType imageType, int imageIndex)
  343. {
  344. if (item == null)
  345. {
  346. throw new ArgumentNullException("item");
  347. }
  348. if (imageType == ImageType.Backdrop)
  349. {
  350. if (item.BackdropImagePaths == null)
  351. {
  352. throw new InvalidOperationException(string.Format("Item {0} does not have any Backdrops.", item.Name));
  353. }
  354. return item.BackdropImagePaths[imageIndex];
  355. }
  356. if (imageType == ImageType.Screenshot)
  357. {
  358. if (item.ScreenshotImagePaths == null)
  359. {
  360. throw new InvalidOperationException(string.Format("Item {0} does not have any Screenshots.", item.Name));
  361. }
  362. return item.ScreenshotImagePaths[imageIndex];
  363. }
  364. if (imageType == ImageType.Chapter)
  365. {
  366. return _itemRepo.GetChapter(item.Id, imageIndex).ImagePath;
  367. }
  368. return item.GetImage(imageType);
  369. }
  370. /// <summary>
  371. /// Gets the image date modified.
  372. /// </summary>
  373. /// <param name="item">The item.</param>
  374. /// <param name="imageType">Type of the image.</param>
  375. /// <param name="imageIndex">Index of the image.</param>
  376. /// <returns>DateTime.</returns>
  377. /// <exception cref="System.ArgumentNullException">item</exception>
  378. public DateTime GetImageDateModified(BaseItem item, ImageType imageType, int imageIndex)
  379. {
  380. if (item == null)
  381. {
  382. throw new ArgumentNullException("item");
  383. }
  384. var imagePath = GetImagePath(item, imageType, imageIndex);
  385. return GetImageDateModified(item, imagePath);
  386. }
  387. /// <summary>
  388. /// Gets the image date modified.
  389. /// </summary>
  390. /// <param name="item">The item.</param>
  391. /// <param name="imagePath">The image path.</param>
  392. /// <returns>DateTime.</returns>
  393. /// <exception cref="System.ArgumentNullException">item</exception>
  394. public DateTime GetImageDateModified(BaseItem item, string imagePath)
  395. {
  396. if (item == null)
  397. {
  398. throw new ArgumentNullException("item");
  399. }
  400. if (string.IsNullOrEmpty(imagePath))
  401. {
  402. throw new ArgumentNullException("imagePath");
  403. }
  404. var metaFileEntry = item.ResolveArgs.GetMetaFileByPath(imagePath);
  405. // If we didn't the metafile entry, check the Season
  406. if (metaFileEntry == null)
  407. {
  408. var episode = item as Episode;
  409. if (episode != null && episode.Season != null)
  410. {
  411. episode.Season.ResolveArgs.GetMetaFileByPath(imagePath);
  412. }
  413. }
  414. // See if we can avoid a file system lookup by looking for the file in ResolveArgs
  415. return metaFileEntry == null ? File.GetLastWriteTimeUtc(imagePath) : metaFileEntry.LastWriteTimeUtc;
  416. }
  417. /// <summary>
  418. /// Crops whitespace from an image, caches the result, and returns the cached path
  419. /// </summary>
  420. /// <param name="originalImagePath">The original image path.</param>
  421. /// <param name="dateModified">The date modified.</param>
  422. /// <returns>System.String.</returns>
  423. private async Task<string> GetCroppedImage(string originalImagePath, DateTime dateModified)
  424. {
  425. var name = originalImagePath;
  426. name += "datemodified=" + dateModified.Ticks;
  427. var croppedImagePath = CroppedImageCache.GetResourcePath(name, Path.GetExtension(originalImagePath));
  428. var semaphore = GetLock(croppedImagePath);
  429. await semaphore.WaitAsync().ConfigureAwait(false);
  430. // Check again in case of contention
  431. if (File.Exists(croppedImagePath))
  432. {
  433. semaphore.Release();
  434. return croppedImagePath;
  435. }
  436. try
  437. {
  438. using (var fileStream = new FileStream(originalImagePath, FileMode.Open, FileAccess.Read, FileShare.Read, StreamDefaults.DefaultFileStreamBufferSize, true))
  439. {
  440. // Copy to memory stream to avoid Image locking file
  441. using (var memoryStream = new MemoryStream())
  442. {
  443. await fileStream.CopyToAsync(memoryStream).ConfigureAwait(false);
  444. using (var originalImage = (Bitmap)Image.FromStream(memoryStream, true, false))
  445. {
  446. var outputFormat = originalImage.RawFormat;
  447. using (var croppedImage = originalImage.CropWhitespace())
  448. {
  449. var parentPath = Path.GetDirectoryName(croppedImagePath);
  450. if (!Directory.Exists(parentPath))
  451. {
  452. Directory.CreateDirectory(parentPath);
  453. }
  454. using (var outputStream = new FileStream(croppedImagePath, FileMode.Create, FileAccess.Write, FileShare.Read))
  455. {
  456. croppedImage.Save(outputFormat, outputStream, 100);
  457. }
  458. }
  459. }
  460. }
  461. }
  462. }
  463. catch (Exception ex)
  464. {
  465. // We have to have a catch-all here because some of the .net image methods throw a plain old Exception
  466. _logger.ErrorException("Error cropping image {0}", ex, originalImagePath);
  467. return originalImagePath;
  468. }
  469. finally
  470. {
  471. semaphore.Release();
  472. }
  473. return croppedImagePath;
  474. }
  475. /// <summary>
  476. /// Gets the enhanced image.
  477. /// </summary>
  478. /// <param name="originalImagePath">The original image path.</param>
  479. /// <param name="dateModified">The date modified.</param>
  480. /// <param name="item">The item.</param>
  481. /// <param name="imageType">Type of the image.</param>
  482. /// <param name="imageIndex">Index of the image.</param>
  483. /// <returns>Task{System.String}.</returns>
  484. /// <exception cref="System.ArgumentNullException">item</exception>
  485. public Task<string> GetEnhancedImage(string originalImagePath, DateTime dateModified, BaseItem item, ImageType imageType, int imageIndex)
  486. {
  487. if (item == null)
  488. {
  489. throw new ArgumentNullException("item");
  490. }
  491. var supportedImageEnhancers = ImageEnhancers.Where(i =>
  492. {
  493. try
  494. {
  495. return i.Supports(item, imageType);
  496. }
  497. catch (Exception ex)
  498. {
  499. _logger.ErrorException("Error in image enhancer: {0}", ex, i.GetType().Name);
  500. return false;
  501. }
  502. }).ToList();
  503. return GetEnhancedImage(originalImagePath, dateModified, item, imageType, imageIndex, supportedImageEnhancers);
  504. }
  505. /// <summary>
  506. /// Runs an image through the image enhancers, caches the result, and returns the cached path
  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="item">The item.</param>
  511. /// <param name="imageType">Type of the image.</param>
  512. /// <param name="imageIndex">Index of the image.</param>
  513. /// <param name="supportedEnhancers">The supported enhancers.</param>
  514. /// <returns>System.String.</returns>
  515. /// <exception cref="System.ArgumentNullException">originalImagePath</exception>
  516. public async Task<string> GetEnhancedImage(string originalImagePath, DateTime dateModified, BaseItem item, ImageType imageType, int imageIndex, IEnumerable<IImageEnhancer> supportedEnhancers)
  517. {
  518. if (string.IsNullOrEmpty(originalImagePath))
  519. {
  520. throw new ArgumentNullException("originalImagePath");
  521. }
  522. if (item == null)
  523. {
  524. throw new ArgumentNullException("item");
  525. }
  526. var cacheGuid = GetImageCacheTag(originalImagePath, dateModified, supportedEnhancers, item, imageType);
  527. // All enhanced images are saved as png to allow transparency
  528. var enhancedImagePath = EnhancedImageCache.GetResourcePath(cacheGuid + ".png");
  529. var semaphore = GetLock(enhancedImagePath);
  530. await semaphore.WaitAsync().ConfigureAwait(false);
  531. // Check again in case of contention
  532. if (File.Exists(enhancedImagePath))
  533. {
  534. semaphore.Release();
  535. return enhancedImagePath;
  536. }
  537. try
  538. {
  539. using (var fileStream = new FileStream(originalImagePath, FileMode.Open, FileAccess.Read, FileShare.Read, StreamDefaults.DefaultFileStreamBufferSize, true))
  540. {
  541. // Copy to memory stream to avoid Image locking file
  542. using (var memoryStream = new MemoryStream())
  543. {
  544. await fileStream.CopyToAsync(memoryStream).ConfigureAwait(false);
  545. using (var originalImage = Image.FromStream(memoryStream, true, false))
  546. {
  547. //Pass the image through registered enhancers
  548. using (var newImage = await ExecuteImageEnhancers(supportedEnhancers, originalImage, item, imageType, imageIndex).ConfigureAwait(false))
  549. {
  550. var parentDirectory = Path.GetDirectoryName(enhancedImagePath);
  551. if (!Directory.Exists(parentDirectory))
  552. {
  553. Directory.CreateDirectory(parentDirectory);
  554. }
  555. //And then save it in the cache
  556. using (var outputStream = new FileStream(enhancedImagePath, FileMode.Create, FileAccess.Write, FileShare.Read))
  557. {
  558. newImage.Save(ImageFormat.Png, outputStream, 100);
  559. }
  560. }
  561. }
  562. }
  563. }
  564. }
  565. finally
  566. {
  567. semaphore.Release();
  568. }
  569. return enhancedImagePath;
  570. }
  571. /// <summary>
  572. /// Gets the image cache tag.
  573. /// </summary>
  574. /// <param name="item">The item.</param>
  575. /// <param name="imageType">Type of the image.</param>
  576. /// <param name="imagePath">The image path.</param>
  577. /// <returns>Guid.</returns>
  578. /// <exception cref="System.ArgumentNullException">item</exception>
  579. public Guid GetImageCacheTag(BaseItem item, ImageType imageType, string imagePath)
  580. {
  581. if (item == null)
  582. {
  583. throw new ArgumentNullException("item");
  584. }
  585. if (string.IsNullOrEmpty(imagePath))
  586. {
  587. throw new ArgumentNullException("imagePath");
  588. }
  589. var dateModified = GetImageDateModified(item, imagePath);
  590. var supportedEnhancers = ImageEnhancers.Where(i =>
  591. {
  592. try
  593. {
  594. return i.Supports(item, imageType);
  595. }
  596. catch (Exception ex)
  597. {
  598. _logger.ErrorException("Error in image enhancer: {0}", ex, i.GetType().Name);
  599. return false;
  600. }
  601. }).ToList();
  602. return GetImageCacheTag(imagePath, dateModified, supportedEnhancers, item, imageType);
  603. }
  604. /// <summary>
  605. /// Gets the image cache tag.
  606. /// </summary>
  607. /// <param name="originalImagePath">The original image path.</param>
  608. /// <param name="dateModified">The date modified of the original image file.</param>
  609. /// <param name="imageEnhancers">The image enhancers.</param>
  610. /// <param name="item">The item.</param>
  611. /// <param name="imageType">Type of the image.</param>
  612. /// <returns>Guid.</returns>
  613. /// <exception cref="System.ArgumentNullException">item</exception>
  614. public Guid GetImageCacheTag(string originalImagePath, DateTime dateModified, IEnumerable<IImageEnhancer> imageEnhancers, BaseItem item, ImageType imageType)
  615. {
  616. if (item == null)
  617. {
  618. throw new ArgumentNullException("item");
  619. }
  620. if (imageEnhancers == null)
  621. {
  622. throw new ArgumentNullException("imageEnhancers");
  623. }
  624. if (string.IsNullOrEmpty(originalImagePath))
  625. {
  626. throw new ArgumentNullException("originalImagePath");
  627. }
  628. // Cache name is created with supported enhancers combined with the last config change so we pick up new config changes
  629. var cacheKeys = imageEnhancers.Select(i => i.GetConfigurationCacheKey(item, imageType)).ToList();
  630. cacheKeys.Add(originalImagePath + dateModified.Ticks);
  631. return string.Join("|", cacheKeys.ToArray()).GetMD5();
  632. }
  633. /// <summary>
  634. /// Executes the image enhancers.
  635. /// </summary>
  636. /// <param name="imageEnhancers">The image enhancers.</param>
  637. /// <param name="originalImage">The original image.</param>
  638. /// <param name="item">The item.</param>
  639. /// <param name="imageType">Type of the image.</param>
  640. /// <param name="imageIndex">Index of the image.</param>
  641. /// <returns>Task{EnhancedImage}.</returns>
  642. private async Task<Image> ExecuteImageEnhancers(IEnumerable<IImageEnhancer> imageEnhancers, Image originalImage, BaseItem item, ImageType imageType, int imageIndex)
  643. {
  644. var result = originalImage;
  645. // Run the enhancers sequentially in order of priority
  646. foreach (var enhancer in imageEnhancers)
  647. {
  648. var typeName = enhancer.GetType().Name;
  649. try
  650. {
  651. result = await enhancer.EnhanceImageAsync(item, result, imageType, imageIndex).ConfigureAwait(false);
  652. }
  653. catch (Exception ex)
  654. {
  655. _logger.ErrorException("{0} failed enhancing {1}", ex, typeName, item.Name);
  656. throw;
  657. }
  658. }
  659. return result;
  660. }
  661. /// <summary>
  662. /// Gets the lock.
  663. /// </summary>
  664. /// <param name="filename">The filename.</param>
  665. /// <returns>System.Object.</returns>
  666. private SemaphoreSlim GetLock(string filename)
  667. {
  668. return _locks.GetOrAdd(filename, key => new SemaphoreSlim(1, 1));
  669. }
  670. }
  671. }