ImageProcessor.cs 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935
  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. #if __MonoCS__
  196. // Mono throw an exeception if assign 0 to SetResolution
  197. if (originalImage.HorizontalResolution != 0 && originalImage.VerticalResolution != 0)
  198. {
  199. // Preserve the original resolution
  200. thumbnail.SetResolution(originalImage.HorizontalResolution, originalImage.VerticalResolution);
  201. }
  202. #else
  203. // Preserve the original resolution
  204. thumbnail.SetResolution(originalImage.HorizontalResolution, originalImage.VerticalResolution);
  205. #endif
  206. using (var thumbnailGraph = Graphics.FromImage(thumbnail))
  207. {
  208. thumbnailGraph.CompositingQuality = CompositingQuality.HighQuality;
  209. thumbnailGraph.SmoothingMode = SmoothingMode.HighQuality;
  210. thumbnailGraph.InterpolationMode = InterpolationMode.HighQualityBicubic;
  211. thumbnailGraph.PixelOffsetMode = PixelOffsetMode.HighQuality;
  212. thumbnailGraph.CompositingMode = string.IsNullOrEmpty(options.BackgroundColor) && !options.PercentPlayed.HasValue && !options.AddPlayedIndicator ? CompositingMode.SourceCopy : CompositingMode.SourceOver;
  213. SetBackgroundColor(thumbnailGraph, options);
  214. thumbnailGraph.DrawImage(originalImage, 0, 0, newWidth, newHeight);
  215. DrawIndicator(thumbnailGraph, newWidth, newHeight, options);
  216. var outputFormat = GetOutputFormat(originalImage, options.OutputFormat);
  217. using (var outputMemoryStream = new MemoryStream())
  218. {
  219. // Save to the memory stream
  220. thumbnail.Save(outputFormat, outputMemoryStream, quality);
  221. var bytes = outputMemoryStream.ToArray();
  222. await toStream.WriteAsync(bytes, 0, bytes.Length).ConfigureAwait(false);
  223. // kick off a task to cache the result
  224. CacheResizedImage(cacheFilePath, bytes, semaphore);
  225. }
  226. }
  227. }
  228. }
  229. }
  230. }
  231. }
  232. catch
  233. {
  234. semaphore.Release();
  235. throw;
  236. }
  237. }
  238. /// <summary>
  239. /// Caches the resized image.
  240. /// </summary>
  241. /// <param name="cacheFilePath">The cache file path.</param>
  242. /// <param name="bytes">The bytes.</param>
  243. /// <param name="semaphore">The semaphore.</param>
  244. private void CacheResizedImage(string cacheFilePath, byte[] bytes, SemaphoreSlim semaphore)
  245. {
  246. Task.Run(async () =>
  247. {
  248. try
  249. {
  250. var parentPath = Path.GetDirectoryName(cacheFilePath);
  251. Directory.CreateDirectory(parentPath);
  252. // Save to the cache location
  253. using (var cacheFileStream = _fileSystem.GetFileStream(cacheFilePath, FileMode.Create, FileAccess.Write, FileShare.Read, true))
  254. {
  255. // Save to the filestream
  256. await cacheFileStream.WriteAsync(bytes, 0, bytes.Length).ConfigureAwait(false);
  257. }
  258. }
  259. catch (Exception ex)
  260. {
  261. _logger.ErrorException("Error writing to image cache file {0}", ex, cacheFilePath);
  262. }
  263. finally
  264. {
  265. semaphore.Release();
  266. }
  267. });
  268. }
  269. /// <summary>
  270. /// Sets the color of the background.
  271. /// </summary>
  272. /// <param name="graphics">The graphics.</param>
  273. /// <param name="options">The options.</param>
  274. private void SetBackgroundColor(Graphics graphics, ImageProcessingOptions options)
  275. {
  276. var color = options.BackgroundColor;
  277. if (!string.IsNullOrEmpty(color))
  278. {
  279. Color drawingColor;
  280. try
  281. {
  282. drawingColor = ColorTranslator.FromHtml(color);
  283. }
  284. catch
  285. {
  286. drawingColor = ColorTranslator.FromHtml("#" + color);
  287. }
  288. graphics.Clear(drawingColor);
  289. }
  290. }
  291. /// <summary>
  292. /// Draws the indicator.
  293. /// </summary>
  294. /// <param name="graphics">The graphics.</param>
  295. /// <param name="imageWidth">Width of the image.</param>
  296. /// <param name="imageHeight">Height of the image.</param>
  297. /// <param name="options">The options.</param>
  298. private void DrawIndicator(Graphics graphics, int imageWidth, int imageHeight, ImageProcessingOptions options)
  299. {
  300. if (!options.AddPlayedIndicator && !options.PercentPlayed.HasValue)
  301. {
  302. return;
  303. }
  304. try
  305. {
  306. var percentOffset = 0;
  307. if (options.AddPlayedIndicator)
  308. {
  309. var currentImageSize = new Size(imageWidth, imageHeight);
  310. new WatchedIndicatorDrawer().Process(graphics, currentImageSize);
  311. percentOffset = 0 - WatchedIndicatorDrawer.IndicatorWidth;
  312. }
  313. if (options.PercentPlayed.HasValue)
  314. {
  315. var currentImageSize = new Size(imageWidth, imageHeight);
  316. new PercentPlayedDrawer().Process(graphics, currentImageSize, options.PercentPlayed.Value, percentOffset);
  317. }
  318. }
  319. catch (Exception ex)
  320. {
  321. _logger.ErrorException("Error drawing indicator overlay", ex);
  322. }
  323. }
  324. /// <summary>
  325. /// Gets the output format.
  326. /// </summary>
  327. /// <param name="image">The image.</param>
  328. /// <param name="outputFormat">The output format.</param>
  329. /// <returns>ImageFormat.</returns>
  330. private ImageFormat GetOutputFormat(Image image, ImageOutputFormat outputFormat)
  331. {
  332. switch (outputFormat)
  333. {
  334. case ImageOutputFormat.Bmp:
  335. return ImageFormat.Bmp;
  336. case ImageOutputFormat.Gif:
  337. return ImageFormat.Gif;
  338. case ImageOutputFormat.Jpg:
  339. return ImageFormat.Jpeg;
  340. case ImageOutputFormat.Png:
  341. return ImageFormat.Png;
  342. default:
  343. return image.RawFormat;
  344. }
  345. }
  346. /// <summary>
  347. /// Crops whitespace from an image, caches the result, and returns the cached path
  348. /// </summary>
  349. /// <param name="originalImagePath">The original image path.</param>
  350. /// <param name="dateModified">The date modified.</param>
  351. /// <returns>System.String.</returns>
  352. private async Task<Tuple<string, DateTime>> GetWhitespaceCroppedImage(string originalImagePath, DateTime dateModified)
  353. {
  354. var name = originalImagePath;
  355. name += "datemodified=" + dateModified.Ticks;
  356. var croppedImagePath = GetCachePath(CroppedWhitespaceImageCachePath, name, Path.GetExtension(originalImagePath));
  357. var semaphore = GetLock(croppedImagePath);
  358. await semaphore.WaitAsync().ConfigureAwait(false);
  359. // Check again in case of contention
  360. if (File.Exists(croppedImagePath))
  361. {
  362. semaphore.Release();
  363. return new Tuple<string, DateTime>(croppedImagePath, _fileSystem.GetLastWriteTimeUtc(croppedImagePath));
  364. }
  365. try
  366. {
  367. using (var fileStream = _fileSystem.GetFileStream(originalImagePath, FileMode.Open, FileAccess.Read, FileShare.Read, true))
  368. {
  369. // Copy to memory stream to avoid Image locking file
  370. using (var memoryStream = new MemoryStream())
  371. {
  372. await fileStream.CopyToAsync(memoryStream).ConfigureAwait(false);
  373. using (var originalImage = (Bitmap)Image.FromStream(memoryStream, true, false))
  374. {
  375. var outputFormat = originalImage.RawFormat;
  376. using (var croppedImage = originalImage.CropWhitespace())
  377. {
  378. Directory.CreateDirectory(Path.GetDirectoryName(croppedImagePath));
  379. using (var outputStream = _fileSystem.GetFileStream(croppedImagePath, FileMode.Create, FileAccess.Write, FileShare.Read, false))
  380. {
  381. croppedImage.Save(outputFormat, outputStream, 100);
  382. }
  383. }
  384. }
  385. }
  386. }
  387. }
  388. catch (Exception ex)
  389. {
  390. // We have to have a catch-all here because some of the .net image methods throw a plain old Exception
  391. _logger.ErrorException("Error cropping image {0}", ex, originalImagePath);
  392. return new Tuple<string, DateTime>(originalImagePath, dateModified);
  393. }
  394. finally
  395. {
  396. semaphore.Release();
  397. }
  398. return new Tuple<string, DateTime>(croppedImagePath, _fileSystem.GetLastWriteTimeUtc(croppedImagePath));
  399. }
  400. /// <summary>
  401. /// Gets the cache file path based on a set of parameters
  402. /// </summary>
  403. private string GetCacheFilePath(string originalPath, ImageSize outputSize, int quality, DateTime dateModified, ImageOutputFormat format, bool addPlayedIndicator, int? percentPlayed, string backgroundColor)
  404. {
  405. var filename = originalPath;
  406. filename += "width=" + outputSize.Width;
  407. filename += "height=" + outputSize.Height;
  408. filename += "quality=" + quality;
  409. filename += "datemodified=" + dateModified.Ticks;
  410. if (format != ImageOutputFormat.Original)
  411. {
  412. filename += "f=" + format;
  413. }
  414. if (addPlayedIndicator)
  415. {
  416. filename += "pl=true";
  417. }
  418. if (percentPlayed.HasValue)
  419. {
  420. filename += "p=" + percentPlayed.Value;
  421. }
  422. if (!string.IsNullOrEmpty(backgroundColor))
  423. {
  424. filename += "b=" + backgroundColor;
  425. }
  426. return GetCachePath(ResizedImageCachePath, filename, Path.GetExtension(originalPath));
  427. }
  428. /// <summary>
  429. /// Gets the size of the image.
  430. /// </summary>
  431. /// <param name="path">The path.</param>
  432. /// <returns>ImageSize.</returns>
  433. public ImageSize GetImageSize(string path)
  434. {
  435. return GetImageSize(path, File.GetLastWriteTimeUtc(path));
  436. }
  437. /// <summary>
  438. /// Gets the size of the image.
  439. /// </summary>
  440. /// <param name="path">The path.</param>
  441. /// <param name="imageDateModified">The image date modified.</param>
  442. /// <returns>ImageSize.</returns>
  443. /// <exception cref="System.ArgumentNullException">path</exception>
  444. public ImageSize GetImageSize(string path, DateTime imageDateModified)
  445. {
  446. if (string.IsNullOrEmpty(path))
  447. {
  448. throw new ArgumentNullException("path");
  449. }
  450. var name = path + "datemodified=" + imageDateModified.Ticks;
  451. ImageSize size;
  452. var cacheHash = name.GetMD5();
  453. if (!_cachedImagedSizes.TryGetValue(cacheHash, out size))
  454. {
  455. size = GetImageSizeInternal(path);
  456. _cachedImagedSizes.AddOrUpdate(cacheHash, size, (keyName, oldValue) => size);
  457. }
  458. return size;
  459. }
  460. /// <summary>
  461. /// Gets the image size internal.
  462. /// </summary>
  463. /// <param name="path">The path.</param>
  464. /// <returns>ImageSize.</returns>
  465. private ImageSize GetImageSizeInternal(string path)
  466. {
  467. var size = ImageHeader.GetDimensions(path, _logger, _fileSystem);
  468. StartSaveImageSizeTimer();
  469. return new ImageSize { Width = size.Width, Height = size.Height };
  470. }
  471. private readonly Timer _saveImageSizeTimer;
  472. private const int SaveImageSizeTimeout = 5000;
  473. private readonly object _saveImageSizeLock = new object();
  474. private void StartSaveImageSizeTimer()
  475. {
  476. _saveImageSizeTimer.Change(SaveImageSizeTimeout, Timeout.Infinite);
  477. }
  478. private void SaveImageSizeCallback(object state)
  479. {
  480. lock (_saveImageSizeLock)
  481. {
  482. try
  483. {
  484. var path = ImageSizeFile;
  485. Directory.CreateDirectory(Path.GetDirectoryName(path));
  486. _jsonSerializer.SerializeToFile(_cachedImagedSizes, path);
  487. }
  488. catch (Exception ex)
  489. {
  490. _logger.ErrorException("Error saving image size file", ex);
  491. }
  492. }
  493. }
  494. private string ImageSizeFile
  495. {
  496. get
  497. {
  498. return Path.Combine(_appPaths.DataPath, "imagesizes.json");
  499. }
  500. }
  501. /// <summary>
  502. /// Gets the image cache tag.
  503. /// </summary>
  504. /// <param name="item">The item.</param>
  505. /// <param name="imageType">Type of the image.</param>
  506. /// <param name="imagePath">The image path.</param>
  507. /// <returns>Guid.</returns>
  508. /// <exception cref="System.ArgumentNullException">item</exception>
  509. public Guid GetImageCacheTag(IHasImages item, ImageType imageType, string imagePath)
  510. {
  511. if (item == null)
  512. {
  513. throw new ArgumentNullException("item");
  514. }
  515. if (string.IsNullOrEmpty(imagePath))
  516. {
  517. throw new ArgumentNullException("imagePath");
  518. }
  519. var dateModified = item.GetImageDateModified(imagePath);
  520. var supportedEnhancers = GetSupportedEnhancers(item, imageType);
  521. return GetImageCacheTag(item, imageType, imagePath, dateModified, supportedEnhancers.ToList());
  522. }
  523. /// <summary>
  524. /// Gets the image cache tag.
  525. /// </summary>
  526. /// <param name="item">The item.</param>
  527. /// <param name="imageType">Type of the image.</param>
  528. /// <param name="originalImagePath">The original image path.</param>
  529. /// <param name="dateModified">The date modified of the original image file.</param>
  530. /// <param name="imageEnhancers">The image enhancers.</param>
  531. /// <returns>Guid.</returns>
  532. /// <exception cref="System.ArgumentNullException">item</exception>
  533. public Guid GetImageCacheTag(IHasImages item, ImageType imageType, string originalImagePath, DateTime dateModified, List<IImageEnhancer> imageEnhancers)
  534. {
  535. if (item == null)
  536. {
  537. throw new ArgumentNullException("item");
  538. }
  539. if (imageEnhancers == null)
  540. {
  541. throw new ArgumentNullException("imageEnhancers");
  542. }
  543. if (string.IsNullOrEmpty(originalImagePath))
  544. {
  545. throw new ArgumentNullException("originalImagePath");
  546. }
  547. // Optimization
  548. if (imageEnhancers.Count == 0)
  549. {
  550. return (originalImagePath + dateModified.Ticks).GetMD5();
  551. }
  552. // Cache name is created with supported enhancers combined with the last config change so we pick up new config changes
  553. var cacheKeys = imageEnhancers.Select(i => i.GetConfigurationCacheKey(item, imageType)).ToList();
  554. cacheKeys.Add(originalImagePath + dateModified.Ticks);
  555. return string.Join("|", cacheKeys.ToArray()).GetMD5();
  556. }
  557. /// <summary>
  558. /// Gets the enhanced image.
  559. /// </summary>
  560. /// <param name="item">The item.</param>
  561. /// <param name="imageType">Type of the image.</param>
  562. /// <param name="imageIndex">Index of the image.</param>
  563. /// <returns>Task{System.String}.</returns>
  564. public async Task<string> GetEnhancedImage(IHasImages item, ImageType imageType, int imageIndex)
  565. {
  566. var enhancers = GetSupportedEnhancers(item, imageType).ToList();
  567. var imagePath = item.GetImagePath(imageType, imageIndex);
  568. var dateModified = item.GetImageDateModified(imagePath);
  569. var result = await GetEnhancedImage(imagePath, dateModified, item, imageType, imageIndex, enhancers);
  570. return result.Item1;
  571. }
  572. private async Task<Tuple<string, DateTime>> GetEnhancedImage(string originalImagePath, DateTime dateModified, IHasImages item,
  573. ImageType imageType, int imageIndex,
  574. List<IImageEnhancer> enhancers)
  575. {
  576. try
  577. {
  578. // Enhance if we have enhancers
  579. var ehnancedImagePath = await GetEnhancedImageInternal(originalImagePath, dateModified, item, imageType, imageIndex, enhancers).ConfigureAwait(false);
  580. // If the path changed update dateModified
  581. if (!ehnancedImagePath.Equals(originalImagePath, StringComparison.OrdinalIgnoreCase))
  582. {
  583. dateModified = _fileSystem.GetLastWriteTimeUtc(ehnancedImagePath);
  584. return new Tuple<string, DateTime>(ehnancedImagePath, dateModified);
  585. }
  586. }
  587. catch (Exception ex)
  588. {
  589. _logger.Error("Error enhancing image", ex);
  590. }
  591. return new Tuple<string, DateTime>(originalImagePath, dateModified);
  592. }
  593. /// <summary>
  594. /// Runs an image through the image enhancers, caches the result, and returns the cached path
  595. /// </summary>
  596. /// <param name="originalImagePath">The original image path.</param>
  597. /// <param name="dateModified">The date modified of the original image file.</param>
  598. /// <param name="item">The item.</param>
  599. /// <param name="imageType">Type of the image.</param>
  600. /// <param name="imageIndex">Index of the image.</param>
  601. /// <param name="supportedEnhancers">The supported enhancers.</param>
  602. /// <returns>System.String.</returns>
  603. /// <exception cref="System.ArgumentNullException">originalImagePath</exception>
  604. private async Task<string> GetEnhancedImageInternal(string originalImagePath, DateTime dateModified, IHasImages item, ImageType imageType, int imageIndex, List<IImageEnhancer> supportedEnhancers)
  605. {
  606. if (string.IsNullOrEmpty(originalImagePath))
  607. {
  608. throw new ArgumentNullException("originalImagePath");
  609. }
  610. if (item == null)
  611. {
  612. throw new ArgumentNullException("item");
  613. }
  614. var cacheGuid = GetImageCacheTag(item, imageType, originalImagePath, dateModified, supportedEnhancers);
  615. // All enhanced images are saved as png to allow transparency
  616. var enhancedImagePath = GetCachePath(EnhancedImageCachePath, cacheGuid + ".png");
  617. var semaphore = GetLock(enhancedImagePath);
  618. await semaphore.WaitAsync().ConfigureAwait(false);
  619. // Check again in case of contention
  620. if (File.Exists(enhancedImagePath))
  621. {
  622. semaphore.Release();
  623. return enhancedImagePath;
  624. }
  625. try
  626. {
  627. using (var fileStream = _fileSystem.GetFileStream(originalImagePath, FileMode.Open, FileAccess.Read, FileShare.Read, true))
  628. {
  629. // Copy to memory stream to avoid Image locking file
  630. using (var memoryStream = new MemoryStream())
  631. {
  632. await fileStream.CopyToAsync(memoryStream).ConfigureAwait(false);
  633. using (var originalImage = Image.FromStream(memoryStream, true, false))
  634. {
  635. //Pass the image through registered enhancers
  636. using (var newImage = await ExecuteImageEnhancers(supportedEnhancers, originalImage, item, imageType, imageIndex).ConfigureAwait(false))
  637. {
  638. var parentDirectory = Path.GetDirectoryName(enhancedImagePath);
  639. Directory.CreateDirectory(parentDirectory);
  640. //And then save it in the cache
  641. using (var outputStream = _fileSystem.GetFileStream(enhancedImagePath, FileMode.Create, FileAccess.Write, FileShare.Read, false))
  642. {
  643. newImage.Save(ImageFormat.Png, outputStream, 100);
  644. }
  645. }
  646. }
  647. }
  648. }
  649. }
  650. finally
  651. {
  652. semaphore.Release();
  653. }
  654. return enhancedImagePath;
  655. }
  656. /// <summary>
  657. /// Executes the image enhancers.
  658. /// </summary>
  659. /// <param name="imageEnhancers">The image enhancers.</param>
  660. /// <param name="originalImage">The original image.</param>
  661. /// <param name="item">The item.</param>
  662. /// <param name="imageType">Type of the image.</param>
  663. /// <param name="imageIndex">Index of the image.</param>
  664. /// <returns>Task{EnhancedImage}.</returns>
  665. private async Task<Image> ExecuteImageEnhancers(IEnumerable<IImageEnhancer> imageEnhancers, Image originalImage, IHasImages item, ImageType imageType, int imageIndex)
  666. {
  667. var result = originalImage;
  668. // Run the enhancers sequentially in order of priority
  669. foreach (var enhancer in imageEnhancers)
  670. {
  671. var typeName = enhancer.GetType().Name;
  672. try
  673. {
  674. result = await enhancer.EnhanceImageAsync(item, result, imageType, imageIndex).ConfigureAwait(false);
  675. }
  676. catch (Exception ex)
  677. {
  678. _logger.ErrorException("{0} failed enhancing {1}", ex, typeName, item.Name);
  679. throw;
  680. }
  681. }
  682. return result;
  683. }
  684. /// <summary>
  685. /// The _semaphoreLocks
  686. /// </summary>
  687. private readonly ConcurrentDictionary<string, object> _locks = new ConcurrentDictionary<string, object>();
  688. /// <summary>
  689. /// Gets the lock.
  690. /// </summary>
  691. /// <param name="filename">The filename.</param>
  692. /// <returns>System.Object.</returns>
  693. private object GetObjectLock(string filename)
  694. {
  695. return _locks.GetOrAdd(filename, key => new object());
  696. }
  697. /// <summary>
  698. /// The _semaphoreLocks
  699. /// </summary>
  700. private readonly ConcurrentDictionary<string, SemaphoreSlim> _semaphoreLocks = new ConcurrentDictionary<string, SemaphoreSlim>();
  701. /// <summary>
  702. /// Gets the lock.
  703. /// </summary>
  704. /// <param name="filename">The filename.</param>
  705. /// <returns>System.Object.</returns>
  706. private SemaphoreSlim GetLock(string filename)
  707. {
  708. return _semaphoreLocks.GetOrAdd(filename, key => new SemaphoreSlim(1, 1));
  709. }
  710. /// <summary>
  711. /// Gets the cache path.
  712. /// </summary>
  713. /// <param name="path">The path.</param>
  714. /// <param name="uniqueName">Name of the unique.</param>
  715. /// <param name="fileExtension">The file extension.</param>
  716. /// <returns>System.String.</returns>
  717. /// <exception cref="System.ArgumentNullException">
  718. /// path
  719. /// or
  720. /// uniqueName
  721. /// or
  722. /// fileExtension
  723. /// </exception>
  724. public string GetCachePath(string path, string uniqueName, string fileExtension)
  725. {
  726. if (string.IsNullOrEmpty(path))
  727. {
  728. throw new ArgumentNullException("path");
  729. }
  730. if (string.IsNullOrEmpty(uniqueName))
  731. {
  732. throw new ArgumentNullException("uniqueName");
  733. }
  734. if (string.IsNullOrEmpty(fileExtension))
  735. {
  736. throw new ArgumentNullException("fileExtension");
  737. }
  738. var filename = uniqueName.GetMD5() + fileExtension;
  739. return GetCachePath(path, filename);
  740. }
  741. /// <summary>
  742. /// Gets the cache path.
  743. /// </summary>
  744. /// <param name="path">The path.</param>
  745. /// <param name="filename">The filename.</param>
  746. /// <returns>System.String.</returns>
  747. /// <exception cref="System.ArgumentNullException">
  748. /// path
  749. /// or
  750. /// filename
  751. /// </exception>
  752. public string GetCachePath(string path, string filename)
  753. {
  754. if (string.IsNullOrEmpty(path))
  755. {
  756. throw new ArgumentNullException("path");
  757. }
  758. if (string.IsNullOrEmpty(filename))
  759. {
  760. throw new ArgumentNullException("filename");
  761. }
  762. var prefix = filename.Substring(0, 1);
  763. path = Path.Combine(path, prefix);
  764. return Path.Combine(path, filename);
  765. }
  766. public IEnumerable<IImageEnhancer> GetSupportedEnhancers(IHasImages item, ImageType imageType)
  767. {
  768. return ImageEnhancers.Where(i =>
  769. {
  770. try
  771. {
  772. return i.Supports(item, imageType);
  773. }
  774. catch (Exception ex)
  775. {
  776. _logger.ErrorException("Error in image enhancer: {0}", ex, i.GetType().Name);
  777. return false;
  778. }
  779. });
  780. }
  781. public void Dispose()
  782. {
  783. _saveImageSizeTimer.Dispose();
  784. }
  785. }
  786. }