ImageProcessor.cs 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952
  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 ImageOutputFormat[] GetSupportedImageOutputFormats()
  114. {
  115. if (_webpAvailable)
  116. {
  117. return new[] { ImageOutputFormat.Webp, ImageOutputFormat.Gif, ImageOutputFormat.Jpg, ImageOutputFormat.Png };
  118. }
  119. return new[] { ImageOutputFormat.Gif, ImageOutputFormat.Jpg, ImageOutputFormat.Png };
  120. }
  121. public async Task<string> ProcessImage(ImageProcessingOptions options)
  122. {
  123. if (options == null)
  124. {
  125. throw new ArgumentNullException("options");
  126. }
  127. var originalImagePath = options.Image.Path;
  128. if (options.HasDefaultOptions(originalImagePath) && options.Enhancers.Count == 0 && !options.CropWhiteSpace)
  129. {
  130. // Just spit out the original file if all the options are default
  131. return originalImagePath;
  132. }
  133. var dateModified = options.Image.DateModified;
  134. if (options.CropWhiteSpace)
  135. {
  136. var tuple = await GetWhitespaceCroppedImage(originalImagePath, dateModified).ConfigureAwait(false);
  137. originalImagePath = tuple.Item1;
  138. dateModified = tuple.Item2;
  139. }
  140. if (options.Enhancers.Count > 0)
  141. {
  142. var tuple = await GetEnhancedImage(options.Image, options.Item, options.ImageIndex, options.Enhancers).ConfigureAwait(false);
  143. originalImagePath = tuple.Item1;
  144. dateModified = tuple.Item2;
  145. }
  146. var originalImageSize = GetImageSize(originalImagePath, dateModified);
  147. // Determine the output size based on incoming parameters
  148. var newSize = DrawingUtils.Resize(originalImageSize, options.Width, options.Height, options.MaxWidth, options.MaxHeight);
  149. if (options.HasDefaultOptionsWithoutSize(originalImagePath) && newSize.Equals(originalImageSize) && options.Enhancers.Count == 0)
  150. {
  151. // Just spit out the original file if the new size equals the old
  152. return originalImagePath;
  153. }
  154. var quality = options.Quality ?? 90;
  155. var cacheFilePath = GetCacheFilePath(originalImagePath, newSize, quality, dateModified, options.OutputFormat, options.AddPlayedIndicator, options.PercentPlayed, options.UnplayedCount, options.BackgroundColor);
  156. var semaphore = GetLock(cacheFilePath);
  157. await semaphore.WaitAsync().ConfigureAwait(false);
  158. // Check again in case of lock contention
  159. try
  160. {
  161. if (File.Exists(cacheFilePath))
  162. {
  163. semaphore.Release();
  164. return cacheFilePath;
  165. }
  166. }
  167. catch
  168. {
  169. semaphore.Release();
  170. throw;
  171. }
  172. try
  173. {
  174. var hasPostProcessing = !string.IsNullOrEmpty(options.BackgroundColor) || options.UnplayedCount.HasValue || options.AddPlayedIndicator || options.PercentPlayed > 0;
  175. using (var fileStream = _fileSystem.GetFileStream(originalImagePath, FileMode.Open, FileAccess.Read, FileShare.Read, true))
  176. {
  177. // Copy to memory stream to avoid Image locking file
  178. using (var memoryStream = new MemoryStream())
  179. {
  180. await fileStream.CopyToAsync(memoryStream).ConfigureAwait(false);
  181. using (var originalImage = Image.FromStream(memoryStream, true, false))
  182. {
  183. var newWidth = Convert.ToInt32(newSize.Width);
  184. var newHeight = Convert.ToInt32(newSize.Height);
  185. var selectedOutputFormat = options.OutputFormat;
  186. _logger.Debug("Processing image to {0}", selectedOutputFormat);
  187. // Graphics.FromImage will throw an exception if the PixelFormat is Indexed, so we need to handle that here
  188. // Also, Webp only supports Format32bppArgb and Format32bppRgb
  189. var pixelFormat = selectedOutputFormat == ImageOutputFormat.Webp
  190. ? PixelFormat.Format32bppArgb
  191. : PixelFormat.Format32bppPArgb;
  192. using (var thumbnail = new Bitmap(newWidth, newHeight, pixelFormat))
  193. {
  194. // Mono throw an exeception if assign 0 to SetResolution
  195. if (originalImage.HorizontalResolution > 0 && originalImage.VerticalResolution > 0)
  196. {
  197. // Preserve the original resolution
  198. thumbnail.SetResolution(originalImage.HorizontalResolution, originalImage.VerticalResolution);
  199. }
  200. using (var thumbnailGraph = Graphics.FromImage(thumbnail))
  201. {
  202. thumbnailGraph.CompositingQuality = CompositingQuality.HighQuality;
  203. thumbnailGraph.SmoothingMode = SmoothingMode.HighQuality;
  204. thumbnailGraph.InterpolationMode = InterpolationMode.HighQualityBicubic;
  205. thumbnailGraph.PixelOffsetMode = PixelOffsetMode.HighQuality;
  206. thumbnailGraph.CompositingMode = !hasPostProcessing ?
  207. CompositingMode.SourceCopy :
  208. CompositingMode.SourceOver;
  209. SetBackgroundColor(thumbnailGraph, options);
  210. thumbnailGraph.DrawImage(originalImage, 0, 0, newWidth, newHeight);
  211. DrawIndicator(thumbnailGraph, newWidth, newHeight, options);
  212. var outputFormat = GetOutputFormat(originalImage, selectedOutputFormat);
  213. Directory.CreateDirectory(Path.GetDirectoryName(cacheFilePath));
  214. // Save to the cache location
  215. using (var cacheFileStream = _fileSystem.GetFileStream(cacheFilePath, FileMode.Create, FileAccess.Write, FileShare.Read, false))
  216. {
  217. if (selectedOutputFormat == ImageOutputFormat.Webp)
  218. {
  219. SaveToWebP(thumbnail, cacheFileStream, quality);
  220. }
  221. else
  222. {
  223. // Save to the memory stream
  224. thumbnail.Save(outputFormat, cacheFileStream, quality);
  225. }
  226. }
  227. return cacheFilePath;
  228. }
  229. }
  230. }
  231. }
  232. }
  233. }
  234. finally
  235. {
  236. semaphore.Release();
  237. }
  238. }
  239. private void SaveToWebP(Bitmap thumbnail, Stream toStream, int quality)
  240. {
  241. new SimpleEncoder().Encode(thumbnail, toStream, quality);
  242. }
  243. private bool _webpAvailable = true;
  244. private void LogWebPVersion()
  245. {
  246. try
  247. {
  248. _logger.Info("libwebp version: " + SimpleEncoder.GetEncoderVersion());
  249. }
  250. catch (Exception ex)
  251. {
  252. _logger.ErrorException("Error loading libwebp: ", ex);
  253. _webpAvailable = false;
  254. }
  255. }
  256. /// <summary>
  257. /// Sets the color of the background.
  258. /// </summary>
  259. /// <param name="graphics">The graphics.</param>
  260. /// <param name="options">The options.</param>
  261. private void SetBackgroundColor(Graphics graphics, ImageProcessingOptions options)
  262. {
  263. var color = options.BackgroundColor;
  264. if (!string.IsNullOrEmpty(color))
  265. {
  266. Color drawingColor;
  267. try
  268. {
  269. drawingColor = ColorTranslator.FromHtml(color);
  270. }
  271. catch
  272. {
  273. drawingColor = ColorTranslator.FromHtml("#" + color);
  274. }
  275. graphics.Clear(drawingColor);
  276. }
  277. }
  278. /// <summary>
  279. /// Draws the indicator.
  280. /// </summary>
  281. /// <param name="graphics">The graphics.</param>
  282. /// <param name="imageWidth">Width of the image.</param>
  283. /// <param name="imageHeight">Height of the image.</param>
  284. /// <param name="options">The options.</param>
  285. private void DrawIndicator(Graphics graphics, int imageWidth, int imageHeight, ImageProcessingOptions options)
  286. {
  287. if (!options.AddPlayedIndicator && !options.UnplayedCount.HasValue && options.PercentPlayed.Equals(0))
  288. {
  289. return;
  290. }
  291. try
  292. {
  293. if (options.AddPlayedIndicator)
  294. {
  295. var currentImageSize = new Size(imageWidth, imageHeight);
  296. new PlayedIndicatorDrawer().DrawPlayedIndicator(graphics, currentImageSize);
  297. }
  298. else if (options.UnplayedCount.HasValue)
  299. {
  300. var currentImageSize = new Size(imageWidth, imageHeight);
  301. new UnplayedCountIndicator().DrawUnplayedCountIndicator(graphics, currentImageSize, options.UnplayedCount.Value);
  302. }
  303. if (options.PercentPlayed >= 0)
  304. {
  305. var currentImageSize = new Size(imageWidth, imageHeight);
  306. new PercentPlayedDrawer().Process(graphics, currentImageSize, options.PercentPlayed);
  307. }
  308. }
  309. catch (Exception ex)
  310. {
  311. _logger.ErrorException("Error drawing indicator overlay", ex);
  312. }
  313. }
  314. /// <summary>
  315. /// Gets the output format.
  316. /// </summary>
  317. /// <param name="image">The image.</param>
  318. /// <param name="outputFormat">The output format.</param>
  319. /// <returns>ImageFormat.</returns>
  320. private System.Drawing.Imaging.ImageFormat GetOutputFormat(Image image, ImageOutputFormat outputFormat)
  321. {
  322. switch (outputFormat)
  323. {
  324. case ImageOutputFormat.Bmp:
  325. return System.Drawing.Imaging.ImageFormat.Bmp;
  326. case ImageOutputFormat.Gif:
  327. return System.Drawing.Imaging.ImageFormat.Gif;
  328. case ImageOutputFormat.Jpg:
  329. return System.Drawing.Imaging.ImageFormat.Jpeg;
  330. case ImageOutputFormat.Png:
  331. return System.Drawing.Imaging.ImageFormat.Png;
  332. default:
  333. return image.RawFormat;
  334. }
  335. }
  336. /// <summary>
  337. /// Crops whitespace from an image, caches the result, and returns the cached path
  338. /// </summary>
  339. /// <param name="originalImagePath">The original image path.</param>
  340. /// <param name="dateModified">The date modified.</param>
  341. /// <returns>System.String.</returns>
  342. private async Task<Tuple<string, DateTime>> GetWhitespaceCroppedImage(string originalImagePath, DateTime dateModified)
  343. {
  344. var name = originalImagePath;
  345. name += "datemodified=" + dateModified.Ticks;
  346. var croppedImagePath = GetCachePath(CroppedWhitespaceImageCachePath, name, Path.GetExtension(originalImagePath));
  347. var semaphore = GetLock(croppedImagePath);
  348. await semaphore.WaitAsync().ConfigureAwait(false);
  349. // Check again in case of contention
  350. if (File.Exists(croppedImagePath))
  351. {
  352. semaphore.Release();
  353. return new Tuple<string, DateTime>(croppedImagePath, _fileSystem.GetLastWriteTimeUtc(croppedImagePath));
  354. }
  355. try
  356. {
  357. using (var fileStream = _fileSystem.GetFileStream(originalImagePath, FileMode.Open, FileAccess.Read, FileShare.Read, true))
  358. {
  359. // Copy to memory stream to avoid Image locking file
  360. using (var memoryStream = new MemoryStream())
  361. {
  362. await fileStream.CopyToAsync(memoryStream).ConfigureAwait(false);
  363. using (var originalImage = (Bitmap)Image.FromStream(memoryStream, true, false))
  364. {
  365. var outputFormat = originalImage.RawFormat;
  366. using (var croppedImage = originalImage.CropWhitespace())
  367. {
  368. Directory.CreateDirectory(Path.GetDirectoryName(croppedImagePath));
  369. using (var outputStream = _fileSystem.GetFileStream(croppedImagePath, FileMode.Create, FileAccess.Write, FileShare.Read, false))
  370. {
  371. croppedImage.Save(outputFormat, outputStream, 100);
  372. }
  373. }
  374. }
  375. }
  376. }
  377. }
  378. catch (Exception ex)
  379. {
  380. // We have to have a catch-all here because some of the .net image methods throw a plain old Exception
  381. _logger.ErrorException("Error cropping image {0}", ex, originalImagePath);
  382. return new Tuple<string, DateTime>(originalImagePath, dateModified);
  383. }
  384. finally
  385. {
  386. semaphore.Release();
  387. }
  388. return new Tuple<string, DateTime>(croppedImagePath, _fileSystem.GetLastWriteTimeUtc(croppedImagePath));
  389. }
  390. /// <summary>
  391. /// Increment this when indicator drawings change
  392. /// </summary>
  393. private const string IndicatorVersion = "2";
  394. /// <summary>
  395. /// Gets the cache file path based on a set of parameters
  396. /// </summary>
  397. private string GetCacheFilePath(string originalPath, ImageSize outputSize, int quality, DateTime dateModified, ImageOutputFormat format, bool addPlayedIndicator, double percentPlayed, int? unwatchedCount, string backgroundColor)
  398. {
  399. var filename = originalPath;
  400. filename += "width=" + outputSize.Width;
  401. filename += "height=" + outputSize.Height;
  402. filename += "quality=" + quality;
  403. filename += "datemodified=" + dateModified.Ticks;
  404. filename += "f=" + format;
  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. }