ImageProcessor.cs 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933
  1. using MediaBrowser.Common.Extensions;
  2. using MediaBrowser.Common.IO;
  3. using MediaBrowser.Controller;
  4. using MediaBrowser.Controller.Drawing;
  5. using MediaBrowser.Controller.Entities;
  6. using MediaBrowser.Controller.MediaEncoding;
  7. using MediaBrowser.Controller.Providers;
  8. using MediaBrowser.Model.Drawing;
  9. using MediaBrowser.Model.Entities;
  10. using MediaBrowser.Model.Logging;
  11. using MediaBrowser.Model.Serialization;
  12. using System;
  13. using System.Collections.Concurrent;
  14. using System.Collections.Generic;
  15. using System.Drawing;
  16. using System.Drawing.Drawing2D;
  17. using System.Drawing.Imaging;
  18. using System.Globalization;
  19. using System.IO;
  20. using System.Linq;
  21. using System.Threading;
  22. using System.Threading.Tasks;
  23. namespace MediaBrowser.Server.Implementations.Drawing
  24. {
  25. /// <summary>
  26. /// Class ImageProcessor
  27. /// </summary>
  28. public class ImageProcessor : IImageProcessor, IDisposable
  29. {
  30. /// <summary>
  31. /// The us culture
  32. /// </summary>
  33. protected readonly CultureInfo UsCulture = new CultureInfo("en-US");
  34. /// <summary>
  35. /// The _cached imaged sizes
  36. /// </summary>
  37. private readonly ConcurrentDictionary<Guid, ImageSize> _cachedImagedSizes;
  38. /// <summary>
  39. /// Gets the list of currently registered image processors
  40. /// Image processors are specialized metadata providers that run after the normal ones
  41. /// </summary>
  42. /// <value>The image enhancers.</value>
  43. public IEnumerable<IImageEnhancer> ImageEnhancers { get; private set; }
  44. /// <summary>
  45. /// The _logger
  46. /// </summary>
  47. private readonly ILogger _logger;
  48. private readonly IFileSystem _fileSystem;
  49. private readonly IJsonSerializer _jsonSerializer;
  50. private readonly IServerApplicationPaths _appPaths;
  51. private readonly IMediaEncoder _mediaEncoder;
  52. public ImageProcessor(ILogger logger, IServerApplicationPaths appPaths, IFileSystem fileSystem, IJsonSerializer jsonSerializer, IMediaEncoder mediaEncoder)
  53. {
  54. _logger = logger;
  55. _fileSystem = fileSystem;
  56. _jsonSerializer = jsonSerializer;
  57. _mediaEncoder = mediaEncoder;
  58. _appPaths = appPaths;
  59. _saveImageSizeTimer = new Timer(SaveImageSizeCallback, null, Timeout.Infinite, Timeout.Infinite);
  60. Dictionary<Guid, ImageSize> sizeDictionary;
  61. try
  62. {
  63. sizeDictionary = jsonSerializer.DeserializeFromFile<Dictionary<Guid, ImageSize>>(ImageSizeFile) ??
  64. new Dictionary<Guid, ImageSize>();
  65. }
  66. catch (FileNotFoundException)
  67. {
  68. // No biggie
  69. sizeDictionary = new Dictionary<Guid, ImageSize>();
  70. }
  71. catch (Exception ex)
  72. {
  73. logger.ErrorException("Error parsing image size cache file", ex);
  74. sizeDictionary = new Dictionary<Guid, ImageSize>();
  75. }
  76. _cachedImagedSizes = new ConcurrentDictionary<Guid, ImageSize>(sizeDictionary);
  77. }
  78. private string ResizedImageCachePath
  79. {
  80. get
  81. {
  82. return Path.Combine(_appPaths.ImageCachePath, "resized-images");
  83. }
  84. }
  85. private string EnhancedImageCachePath
  86. {
  87. get
  88. {
  89. return Path.Combine(_appPaths.ImageCachePath, "enhanced-images");
  90. }
  91. }
  92. private string CroppedWhitespaceImageCachePath
  93. {
  94. get
  95. {
  96. return Path.Combine(_appPaths.ImageCachePath, "cropped-images");
  97. }
  98. }
  99. public void AddParts(IEnumerable<IImageEnhancer> enhancers)
  100. {
  101. ImageEnhancers = enhancers.ToArray();
  102. }
  103. public async Task ProcessImage(ImageProcessingOptions options, Stream toStream)
  104. {
  105. var file = await ProcessImage(options).ConfigureAwait(false);
  106. using (var fileStream = _fileSystem.GetFileStream(file, FileMode.Open, FileAccess.Read, FileShare.Read, true))
  107. {
  108. await fileStream.CopyToAsync(toStream).ConfigureAwait(false);
  109. }
  110. }
  111. public async Task<string> ProcessImage(ImageProcessingOptions options)
  112. {
  113. if (options == null)
  114. {
  115. throw new ArgumentNullException("options");
  116. }
  117. var originalImagePath = options.Image.Path;
  118. if (options.HasDefaultOptions() && options.Enhancers.Count == 0 && !options.CropWhiteSpace)
  119. {
  120. // Just spit out the original file if all the options are default
  121. return originalImagePath;
  122. }
  123. var dateModified = options.Image.DateModified;
  124. if (options.CropWhiteSpace)
  125. {
  126. var tuple = await GetWhitespaceCroppedImage(originalImagePath, dateModified).ConfigureAwait(false);
  127. originalImagePath = tuple.Item1;
  128. dateModified = tuple.Item2;
  129. }
  130. if (options.Enhancers.Count > 0)
  131. {
  132. var tuple = await GetEnhancedImage(options.Image, options.Item, options.ImageIndex, options.Enhancers).ConfigureAwait(false);
  133. originalImagePath = tuple.Item1;
  134. dateModified = tuple.Item2;
  135. }
  136. var originalImageSize = GetImageSize(originalImagePath, dateModified);
  137. // Determine the output size based on incoming parameters
  138. var newSize = DrawingUtils.Resize(originalImageSize, options.Width, options.Height, options.MaxWidth, options.MaxHeight);
  139. if (options.HasDefaultOptionsWithoutSize() && newSize.Equals(originalImageSize) && options.Enhancers.Count == 0)
  140. {
  141. // Just spit out the original file if the new size equals the old
  142. return originalImagePath;
  143. }
  144. var quality = options.Quality ?? 90;
  145. var cacheFilePath = GetCacheFilePath(originalImagePath, newSize, quality, dateModified, options.OutputFormat, options.AddPlayedIndicator, options.PercentPlayed, options.UnplayedCount, options.BackgroundColor);
  146. var semaphore = GetLock(cacheFilePath);
  147. await semaphore.WaitAsync().ConfigureAwait(false);
  148. // Check again in case of lock contention
  149. try
  150. {
  151. if (File.Exists(cacheFilePath))
  152. {
  153. semaphore.Release();
  154. return cacheFilePath;
  155. }
  156. }
  157. catch
  158. {
  159. semaphore.Release();
  160. throw;
  161. }
  162. try
  163. {
  164. var hasPostProcessing = !string.IsNullOrEmpty(options.BackgroundColor) || options.UnplayedCount.HasValue || options.AddPlayedIndicator || options.PercentPlayed.HasValue;
  165. using (var fileStream = _fileSystem.GetFileStream(originalImagePath, FileMode.Open, FileAccess.Read, FileShare.Read, true))
  166. {
  167. // Copy to memory stream to avoid Image locking file
  168. using (var memoryStream = new MemoryStream())
  169. {
  170. await fileStream.CopyToAsync(memoryStream).ConfigureAwait(false);
  171. using (var originalImage = Image.FromStream(memoryStream, true, false))
  172. {
  173. var newWidth = Convert.ToInt32(newSize.Width);
  174. var newHeight = Convert.ToInt32(newSize.Height);
  175. // Graphics.FromImage will throw an exception if the PixelFormat is Indexed, so we need to handle that here
  176. using (var thumbnail = new Bitmap(newWidth, newHeight, PixelFormat.Format32bppPArgb))
  177. {
  178. // Mono throw an exeception if assign 0 to SetResolution
  179. if (originalImage.HorizontalResolution > 0 && originalImage.VerticalResolution > 0)
  180. {
  181. // Preserve the original resolution
  182. thumbnail.SetResolution(originalImage.HorizontalResolution, originalImage.VerticalResolution);
  183. }
  184. using (var thumbnailGraph = Graphics.FromImage(thumbnail))
  185. {
  186. thumbnailGraph.CompositingQuality = CompositingQuality.HighQuality;
  187. thumbnailGraph.SmoothingMode = SmoothingMode.HighQuality;
  188. thumbnailGraph.InterpolationMode = InterpolationMode.HighQualityBicubic;
  189. thumbnailGraph.PixelOffsetMode = PixelOffsetMode.HighQuality;
  190. thumbnailGraph.CompositingMode = !hasPostProcessing ?
  191. CompositingMode.SourceCopy :
  192. CompositingMode.SourceOver;
  193. SetBackgroundColor(thumbnailGraph, options);
  194. thumbnailGraph.DrawImage(originalImage, 0, 0, newWidth, newHeight);
  195. DrawIndicator(thumbnailGraph, newWidth, newHeight, options);
  196. var outputFormat = GetOutputFormat(originalImage, options.OutputFormat);
  197. Directory.CreateDirectory(Path.GetDirectoryName(cacheFilePath));
  198. // Save to the cache location
  199. using (var cacheFileStream = _fileSystem.GetFileStream(cacheFilePath, FileMode.Create, FileAccess.Write, FileShare.Read, false))
  200. {
  201. // Save to the memory stream
  202. thumbnail.Save(outputFormat, cacheFileStream, quality);
  203. }
  204. return cacheFilePath;
  205. }
  206. }
  207. }
  208. }
  209. }
  210. }
  211. finally
  212. {
  213. semaphore.Release();
  214. }
  215. }
  216. /// <summary>
  217. /// Caches the resized image.
  218. /// </summary>
  219. /// <param name="cacheFilePath">The cache file path.</param>
  220. /// <param name="bytes">The bytes.</param>
  221. /// <returns>Task.</returns>
  222. private async Task CacheResizedImage(string cacheFilePath, byte[] bytes)
  223. {
  224. try
  225. {
  226. Directory.CreateDirectory(Path.GetDirectoryName(cacheFilePath));
  227. // Save to the cache location
  228. using (var cacheFileStream = _fileSystem.GetFileStream(cacheFilePath, FileMode.Create, FileAccess.Write, FileShare.Read, true))
  229. {
  230. // Save to the filestream
  231. await cacheFileStream.WriteAsync(bytes, 0, bytes.Length).ConfigureAwait(false);
  232. }
  233. }
  234. catch (Exception ex)
  235. {
  236. _logger.ErrorException("Error writing to image cache file {0}", ex, cacheFilePath);
  237. }
  238. }
  239. /// <summary>
  240. /// Sets the color of the background.
  241. /// </summary>
  242. /// <param name="graphics">The graphics.</param>
  243. /// <param name="options">The options.</param>
  244. private void SetBackgroundColor(Graphics graphics, ImageProcessingOptions options)
  245. {
  246. var color = options.BackgroundColor;
  247. if (!string.IsNullOrEmpty(color))
  248. {
  249. Color drawingColor;
  250. try
  251. {
  252. drawingColor = ColorTranslator.FromHtml(color);
  253. }
  254. catch
  255. {
  256. drawingColor = ColorTranslator.FromHtml("#" + color);
  257. }
  258. graphics.Clear(drawingColor);
  259. }
  260. }
  261. /// <summary>
  262. /// Draws the indicator.
  263. /// </summary>
  264. /// <param name="graphics">The graphics.</param>
  265. /// <param name="imageWidth">Width of the image.</param>
  266. /// <param name="imageHeight">Height of the image.</param>
  267. /// <param name="options">The options.</param>
  268. private void DrawIndicator(Graphics graphics, int imageWidth, int imageHeight, ImageProcessingOptions options)
  269. {
  270. if (!options.AddPlayedIndicator && !options.UnplayedCount.HasValue && !options.PercentPlayed.HasValue)
  271. {
  272. return;
  273. }
  274. try
  275. {
  276. if (options.AddPlayedIndicator)
  277. {
  278. var currentImageSize = new Size(imageWidth, imageHeight);
  279. new PlayedIndicatorDrawer().DrawPlayedIndicator(graphics, currentImageSize);
  280. }
  281. else if (options.UnplayedCount.HasValue)
  282. {
  283. var currentImageSize = new Size(imageWidth, imageHeight);
  284. new UnplayedCountIndicator().DrawUnplayedCountIndicator(graphics, currentImageSize, options.UnplayedCount.Value);
  285. }
  286. if (options.PercentPlayed.HasValue)
  287. {
  288. var currentImageSize = new Size(imageWidth, imageHeight);
  289. new PercentPlayedDrawer().Process(graphics, currentImageSize, options.PercentPlayed.Value);
  290. }
  291. }
  292. catch (Exception ex)
  293. {
  294. _logger.ErrorException("Error drawing indicator overlay", ex);
  295. }
  296. }
  297. /// <summary>
  298. /// Gets the output format.
  299. /// </summary>
  300. /// <param name="image">The image.</param>
  301. /// <param name="outputFormat">The output format.</param>
  302. /// <returns>ImageFormat.</returns>
  303. private System.Drawing.Imaging.ImageFormat GetOutputFormat(Image image, ImageOutputFormat outputFormat)
  304. {
  305. switch (outputFormat)
  306. {
  307. case ImageOutputFormat.Bmp:
  308. return System.Drawing.Imaging.ImageFormat.Bmp;
  309. case ImageOutputFormat.Gif:
  310. return System.Drawing.Imaging.ImageFormat.Gif;
  311. case ImageOutputFormat.Jpg:
  312. return System.Drawing.Imaging.ImageFormat.Jpeg;
  313. case ImageOutputFormat.Png:
  314. return System.Drawing.Imaging.ImageFormat.Png;
  315. default:
  316. return image.RawFormat;
  317. }
  318. }
  319. /// <summary>
  320. /// Crops whitespace from an image, caches the result, and returns the cached path
  321. /// </summary>
  322. /// <param name="originalImagePath">The original image path.</param>
  323. /// <param name="dateModified">The date modified.</param>
  324. /// <returns>System.String.</returns>
  325. private async Task<Tuple<string, DateTime>> GetWhitespaceCroppedImage(string originalImagePath, DateTime dateModified)
  326. {
  327. var name = originalImagePath;
  328. name += "datemodified=" + dateModified.Ticks;
  329. var croppedImagePath = GetCachePath(CroppedWhitespaceImageCachePath, name, Path.GetExtension(originalImagePath));
  330. var semaphore = GetLock(croppedImagePath);
  331. await semaphore.WaitAsync().ConfigureAwait(false);
  332. // Check again in case of contention
  333. if (File.Exists(croppedImagePath))
  334. {
  335. semaphore.Release();
  336. return new Tuple<string, DateTime>(croppedImagePath, _fileSystem.GetLastWriteTimeUtc(croppedImagePath));
  337. }
  338. try
  339. {
  340. using (var fileStream = _fileSystem.GetFileStream(originalImagePath, FileMode.Open, FileAccess.Read, FileShare.Read, true))
  341. {
  342. // Copy to memory stream to avoid Image locking file
  343. using (var memoryStream = new MemoryStream())
  344. {
  345. await fileStream.CopyToAsync(memoryStream).ConfigureAwait(false);
  346. using (var originalImage = (Bitmap)Image.FromStream(memoryStream, true, false))
  347. {
  348. var outputFormat = originalImage.RawFormat;
  349. using (var croppedImage = originalImage.CropWhitespace())
  350. {
  351. Directory.CreateDirectory(Path.GetDirectoryName(croppedImagePath));
  352. using (var outputStream = _fileSystem.GetFileStream(croppedImagePath, FileMode.Create, FileAccess.Write, FileShare.Read, false))
  353. {
  354. croppedImage.Save(outputFormat, outputStream, 100);
  355. }
  356. }
  357. }
  358. }
  359. }
  360. }
  361. catch (Exception ex)
  362. {
  363. // We have to have a catch-all here because some of the .net image methods throw a plain old Exception
  364. _logger.ErrorException("Error cropping image {0}", ex, originalImagePath);
  365. return new Tuple<string, DateTime>(originalImagePath, dateModified);
  366. }
  367. finally
  368. {
  369. semaphore.Release();
  370. }
  371. return new Tuple<string, DateTime>(croppedImagePath, _fileSystem.GetLastWriteTimeUtc(croppedImagePath));
  372. }
  373. /// <summary>
  374. /// Increment this when indicator drawings change
  375. /// </summary>
  376. private const string IndicatorVersion = "2";
  377. /// <summary>
  378. /// Gets the cache file path based on a set of parameters
  379. /// </summary>
  380. private string GetCacheFilePath(string originalPath, ImageSize outputSize, int quality, DateTime dateModified, ImageOutputFormat format, bool addPlayedIndicator, double? percentPlayed, int? unwatchedCount, string backgroundColor)
  381. {
  382. var filename = originalPath;
  383. filename += "width=" + outputSize.Width;
  384. filename += "height=" + outputSize.Height;
  385. filename += "quality=" + quality;
  386. filename += "datemodified=" + dateModified.Ticks;
  387. if (format != ImageOutputFormat.Original)
  388. {
  389. filename += "f=" + format;
  390. }
  391. var hasIndicator = false;
  392. if (addPlayedIndicator)
  393. {
  394. filename += "pl=true";
  395. hasIndicator = true;
  396. }
  397. if (percentPlayed.HasValue)
  398. {
  399. filename += "p=" + percentPlayed.Value;
  400. hasIndicator = true;
  401. }
  402. if (unwatchedCount.HasValue)
  403. {
  404. filename += "p=" + unwatchedCount.Value;
  405. hasIndicator = true;
  406. }
  407. if (hasIndicator)
  408. {
  409. filename += "iv=" + IndicatorVersion;
  410. }
  411. if (!string.IsNullOrEmpty(backgroundColor))
  412. {
  413. filename += "b=" + backgroundColor;
  414. }
  415. return GetCachePath(ResizedImageCachePath, filename, Path.GetExtension(originalPath));
  416. }
  417. /// <summary>
  418. /// Gets the size of the image.
  419. /// </summary>
  420. /// <param name="path">The path.</param>
  421. /// <returns>ImageSize.</returns>
  422. public ImageSize GetImageSize(string path)
  423. {
  424. return GetImageSize(path, File.GetLastWriteTimeUtc(path));
  425. }
  426. /// <summary>
  427. /// Gets the size of the image.
  428. /// </summary>
  429. /// <param name="path">The path.</param>
  430. /// <param name="imageDateModified">The image date modified.</param>
  431. /// <returns>ImageSize.</returns>
  432. /// <exception cref="System.ArgumentNullException">path</exception>
  433. public ImageSize GetImageSize(string path, DateTime imageDateModified)
  434. {
  435. if (string.IsNullOrEmpty(path))
  436. {
  437. throw new ArgumentNullException("path");
  438. }
  439. var name = path + "datemodified=" + imageDateModified.Ticks;
  440. ImageSize size;
  441. var cacheHash = name.GetMD5();
  442. if (!_cachedImagedSizes.TryGetValue(cacheHash, out size))
  443. {
  444. size = GetImageSizeInternal(path);
  445. _cachedImagedSizes.AddOrUpdate(cacheHash, size, (keyName, oldValue) => size);
  446. }
  447. return size;
  448. }
  449. /// <summary>
  450. /// Gets the image size internal.
  451. /// </summary>
  452. /// <param name="path">The path.</param>
  453. /// <returns>ImageSize.</returns>
  454. private ImageSize GetImageSizeInternal(string path)
  455. {
  456. var size = ImageHeader.GetDimensions(path, _logger, _fileSystem);
  457. StartSaveImageSizeTimer();
  458. return new ImageSize { Width = size.Width, Height = size.Height };
  459. }
  460. private readonly Timer _saveImageSizeTimer;
  461. private const int SaveImageSizeTimeout = 5000;
  462. private readonly object _saveImageSizeLock = new object();
  463. private void StartSaveImageSizeTimer()
  464. {
  465. _saveImageSizeTimer.Change(SaveImageSizeTimeout, Timeout.Infinite);
  466. }
  467. private void SaveImageSizeCallback(object state)
  468. {
  469. lock (_saveImageSizeLock)
  470. {
  471. try
  472. {
  473. var path = ImageSizeFile;
  474. Directory.CreateDirectory(Path.GetDirectoryName(path));
  475. _jsonSerializer.SerializeToFile(_cachedImagedSizes, path);
  476. }
  477. catch (Exception ex)
  478. {
  479. _logger.ErrorException("Error saving image size file", ex);
  480. }
  481. }
  482. }
  483. private string ImageSizeFile
  484. {
  485. get
  486. {
  487. return Path.Combine(_appPaths.DataPath, "imagesizes.json");
  488. }
  489. }
  490. /// <summary>
  491. /// Gets the image cache tag.
  492. /// </summary>
  493. /// <param name="item">The item.</param>
  494. /// <param name="image">The image.</param>
  495. /// <returns>Guid.</returns>
  496. /// <exception cref="System.ArgumentNullException">item</exception>
  497. public string GetImageCacheTag(IHasImages item, ItemImageInfo image)
  498. {
  499. if (item == null)
  500. {
  501. throw new ArgumentNullException("item");
  502. }
  503. if (image == null)
  504. {
  505. throw new ArgumentNullException("image");
  506. }
  507. var supportedEnhancers = GetSupportedEnhancers(item, image.Type);
  508. return GetImageCacheTag(item, image, supportedEnhancers.ToList());
  509. }
  510. /// <summary>
  511. /// Gets the image cache tag.
  512. /// </summary>
  513. /// <param name="item">The item.</param>
  514. /// <param name="image">The image.</param>
  515. /// <param name="imageEnhancers">The image enhancers.</param>
  516. /// <returns>Guid.</returns>
  517. /// <exception cref="System.ArgumentNullException">item</exception>
  518. public string GetImageCacheTag(IHasImages item, ItemImageInfo image, List<IImageEnhancer> imageEnhancers)
  519. {
  520. if (item == null)
  521. {
  522. throw new ArgumentNullException("item");
  523. }
  524. if (imageEnhancers == null)
  525. {
  526. throw new ArgumentNullException("imageEnhancers");
  527. }
  528. if (image == null)
  529. {
  530. throw new ArgumentNullException("image");
  531. }
  532. var originalImagePath = image.Path;
  533. var dateModified = image.DateModified;
  534. var imageType = image.Type;
  535. // Optimization
  536. if (imageEnhancers.Count == 0)
  537. {
  538. return (originalImagePath + dateModified.Ticks).GetMD5().ToString("N");
  539. }
  540. // Cache name is created with supported enhancers combined with the last config change so we pick up new config changes
  541. var cacheKeys = imageEnhancers.Select(i => i.GetConfigurationCacheKey(item, imageType)).ToList();
  542. cacheKeys.Add(originalImagePath + dateModified.Ticks);
  543. return string.Join("|", cacheKeys.ToArray()).GetMD5().ToString("N");
  544. }
  545. /// <summary>
  546. /// Gets the enhanced image.
  547. /// </summary>
  548. /// <param name="item">The item.</param>
  549. /// <param name="imageType">Type of the image.</param>
  550. /// <param name="imageIndex">Index of the image.</param>
  551. /// <returns>Task{System.String}.</returns>
  552. public async Task<string> GetEnhancedImage(IHasImages item, ImageType imageType, int imageIndex)
  553. {
  554. var enhancers = GetSupportedEnhancers(item, imageType).ToList();
  555. var imageInfo = item.GetImageInfo(imageType, imageIndex);
  556. var result = await GetEnhancedImage(imageInfo, item, imageIndex, enhancers);
  557. return result.Item1;
  558. }
  559. private async Task<Tuple<string, DateTime>> GetEnhancedImage(ItemImageInfo image,
  560. IHasImages item,
  561. int imageIndex,
  562. List<IImageEnhancer> enhancers)
  563. {
  564. var originalImagePath = image.Path;
  565. var dateModified = image.DateModified;
  566. var imageType = image.Type;
  567. try
  568. {
  569. var cacheGuid = GetImageCacheTag(item, image, enhancers);
  570. // Enhance if we have enhancers
  571. var ehnancedImagePath = await GetEnhancedImageInternal(originalImagePath, item, imageType, imageIndex, enhancers, cacheGuid).ConfigureAwait(false);
  572. // If the path changed update dateModified
  573. if (!ehnancedImagePath.Equals(originalImagePath, StringComparison.OrdinalIgnoreCase))
  574. {
  575. dateModified = _fileSystem.GetLastWriteTimeUtc(ehnancedImagePath);
  576. return new Tuple<string, DateTime>(ehnancedImagePath, dateModified);
  577. }
  578. }
  579. catch (Exception ex)
  580. {
  581. _logger.Error("Error enhancing image", ex);
  582. }
  583. return new Tuple<string, DateTime>(originalImagePath, dateModified);
  584. }
  585. /// <summary>
  586. /// Runs an image through the image enhancers, caches the result, and returns the cached path
  587. /// </summary>
  588. /// <param name="originalImagePath">The original image path.</param>
  589. /// <param name="item">The item.</param>
  590. /// <param name="imageType">Type of the image.</param>
  591. /// <param name="imageIndex">Index of the image.</param>
  592. /// <param name="supportedEnhancers">The supported enhancers.</param>
  593. /// <param name="cacheGuid">The cache unique identifier.</param>
  594. /// <returns>System.String.</returns>
  595. /// <exception cref="System.ArgumentNullException">originalImagePath</exception>
  596. private async Task<string> GetEnhancedImageInternal(string originalImagePath,
  597. IHasImages item,
  598. ImageType imageType,
  599. int imageIndex,
  600. IEnumerable<IImageEnhancer> supportedEnhancers,
  601. string cacheGuid)
  602. {
  603. if (string.IsNullOrEmpty(originalImagePath))
  604. {
  605. throw new ArgumentNullException("originalImagePath");
  606. }
  607. if (item == null)
  608. {
  609. throw new ArgumentNullException("item");
  610. }
  611. // All enhanced images are saved as png to allow transparency
  612. var enhancedImagePath = GetCachePath(EnhancedImageCachePath, cacheGuid + ".png");
  613. var semaphore = GetLock(enhancedImagePath);
  614. await semaphore.WaitAsync().ConfigureAwait(false);
  615. // Check again in case of contention
  616. if (File.Exists(enhancedImagePath))
  617. {
  618. semaphore.Release();
  619. return enhancedImagePath;
  620. }
  621. try
  622. {
  623. using (var fileStream = _fileSystem.GetFileStream(originalImagePath, FileMode.Open, FileAccess.Read, FileShare.Read, true))
  624. {
  625. // Copy to memory stream to avoid Image locking file
  626. using (var memoryStream = new MemoryStream())
  627. {
  628. await fileStream.CopyToAsync(memoryStream).ConfigureAwait(false);
  629. using (var originalImage = Image.FromStream(memoryStream, true, false))
  630. {
  631. //Pass the image through registered enhancers
  632. using (var newImage = await ExecuteImageEnhancers(supportedEnhancers, originalImage, item, imageType, imageIndex).ConfigureAwait(false))
  633. {
  634. var parentDirectory = Path.GetDirectoryName(enhancedImagePath);
  635. Directory.CreateDirectory(parentDirectory);
  636. //And then save it in the cache
  637. using (var outputStream = _fileSystem.GetFileStream(enhancedImagePath, FileMode.Create, FileAccess.Write, FileShare.Read, false))
  638. {
  639. newImage.Save(System.Drawing.Imaging.ImageFormat.Png, outputStream, 100);
  640. }
  641. }
  642. }
  643. }
  644. }
  645. }
  646. finally
  647. {
  648. semaphore.Release();
  649. }
  650. return enhancedImagePath;
  651. }
  652. /// <summary>
  653. /// Executes the image enhancers.
  654. /// </summary>
  655. /// <param name="imageEnhancers">The image enhancers.</param>
  656. /// <param name="originalImage">The original image.</param>
  657. /// <param name="item">The item.</param>
  658. /// <param name="imageType">Type of the image.</param>
  659. /// <param name="imageIndex">Index of the image.</param>
  660. /// <returns>Task{EnhancedImage}.</returns>
  661. private async Task<Image> ExecuteImageEnhancers(IEnumerable<IImageEnhancer> imageEnhancers, Image originalImage, IHasImages item, ImageType imageType, int imageIndex)
  662. {
  663. var result = originalImage;
  664. // Run the enhancers sequentially in order of priority
  665. foreach (var enhancer in imageEnhancers)
  666. {
  667. var typeName = enhancer.GetType().Name;
  668. try
  669. {
  670. result = await enhancer.EnhanceImageAsync(item, result, imageType, imageIndex).ConfigureAwait(false);
  671. }
  672. catch (Exception ex)
  673. {
  674. _logger.ErrorException("{0} failed enhancing {1}", ex, typeName, item.Name);
  675. throw;
  676. }
  677. }
  678. return result;
  679. }
  680. /// <summary>
  681. /// The _semaphoreLocks
  682. /// </summary>
  683. private readonly ConcurrentDictionary<string, object> _locks = new ConcurrentDictionary<string, object>();
  684. /// <summary>
  685. /// Gets the lock.
  686. /// </summary>
  687. /// <param name="filename">The filename.</param>
  688. /// <returns>System.Object.</returns>
  689. private object GetObjectLock(string filename)
  690. {
  691. return _locks.GetOrAdd(filename, key => new object());
  692. }
  693. /// <summary>
  694. /// The _semaphoreLocks
  695. /// </summary>
  696. private readonly ConcurrentDictionary<string, SemaphoreSlim> _semaphoreLocks = new ConcurrentDictionary<string, SemaphoreSlim>();
  697. /// <summary>
  698. /// Gets the lock.
  699. /// </summary>
  700. /// <param name="filename">The filename.</param>
  701. /// <returns>System.Object.</returns>
  702. private SemaphoreSlim GetLock(string filename)
  703. {
  704. return _semaphoreLocks.GetOrAdd(filename, key => new SemaphoreSlim(1, 1));
  705. }
  706. /// <summary>
  707. /// Gets the cache path.
  708. /// </summary>
  709. /// <param name="path">The path.</param>
  710. /// <param name="uniqueName">Name of the unique.</param>
  711. /// <param name="fileExtension">The file extension.</param>
  712. /// <returns>System.String.</returns>
  713. /// <exception cref="System.ArgumentNullException">
  714. /// path
  715. /// or
  716. /// uniqueName
  717. /// or
  718. /// fileExtension
  719. /// </exception>
  720. public string GetCachePath(string path, string uniqueName, string fileExtension)
  721. {
  722. if (string.IsNullOrEmpty(path))
  723. {
  724. throw new ArgumentNullException("path");
  725. }
  726. if (string.IsNullOrEmpty(uniqueName))
  727. {
  728. throw new ArgumentNullException("uniqueName");
  729. }
  730. if (string.IsNullOrEmpty(fileExtension))
  731. {
  732. throw new ArgumentNullException("fileExtension");
  733. }
  734. var filename = uniqueName.GetMD5() + fileExtension;
  735. return GetCachePath(path, filename);
  736. }
  737. /// <summary>
  738. /// Gets the cache path.
  739. /// </summary>
  740. /// <param name="path">The path.</param>
  741. /// <param name="filename">The filename.</param>
  742. /// <returns>System.String.</returns>
  743. /// <exception cref="System.ArgumentNullException">
  744. /// path
  745. /// or
  746. /// filename
  747. /// </exception>
  748. public string GetCachePath(string path, string filename)
  749. {
  750. if (string.IsNullOrEmpty(path))
  751. {
  752. throw new ArgumentNullException("path");
  753. }
  754. if (string.IsNullOrEmpty(filename))
  755. {
  756. throw new ArgumentNullException("filename");
  757. }
  758. var prefix = filename.Substring(0, 1);
  759. path = Path.Combine(path, prefix);
  760. return Path.Combine(path, filename);
  761. }
  762. public IEnumerable<IImageEnhancer> GetSupportedEnhancers(IHasImages item, ImageType imageType)
  763. {
  764. return ImageEnhancers.Where(i =>
  765. {
  766. try
  767. {
  768. return i.Supports(item, imageType);
  769. }
  770. catch (Exception ex)
  771. {
  772. _logger.ErrorException("Error in image enhancer: {0}", ex, i.GetType().Name);
  773. return false;
  774. }
  775. });
  776. }
  777. public void Dispose()
  778. {
  779. _saveImageSizeTimer.Dispose();
  780. }
  781. }
  782. }