ImageProcessor.cs 35 KB

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