ImageProcessor.cs 36 KB

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