ImageManager.cs 32 KB

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