ImageProcessor.cs 35 KB

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