2
0

ImageProcessor.cs 36 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953
  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 System.Drawing.Imaging.ImageFormat GetOutputFormat(Image image, ImageOutputFormat outputFormat)
  331. {
  332. switch (outputFormat)
  333. {
  334. case ImageOutputFormat.Bmp:
  335. return System.Drawing.Imaging.ImageFormat.Bmp;
  336. case ImageOutputFormat.Gif:
  337. return System.Drawing.Imaging.ImageFormat.Gif;
  338. case ImageOutputFormat.Jpg:
  339. return System.Drawing.Imaging.ImageFormat.Jpeg;
  340. case ImageOutputFormat.Png:
  341. return System.Drawing.Imaging.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="image">The image.</param>
  522. /// <returns>Guid.</returns>
  523. /// <exception cref="System.ArgumentNullException">item</exception>
  524. public Guid GetImageCacheTag(IHasImages item, ItemImageInfo image)
  525. {
  526. if (item == null)
  527. {
  528. throw new ArgumentNullException("item");
  529. }
  530. if (image == null)
  531. {
  532. throw new ArgumentNullException("image");
  533. }
  534. var supportedEnhancers = GetSupportedEnhancers(item, image.Type);
  535. return GetImageCacheTag(item, image.Type, image.Path, image.DateModified, supportedEnhancers.ToList());
  536. }
  537. /// <summary>
  538. /// Gets the image cache tag.
  539. /// </summary>
  540. /// <param name="item">The item.</param>
  541. /// <param name="imageType">Type of the image.</param>
  542. /// <param name="originalImagePath">The original image path.</param>
  543. /// <param name="dateModified">The date modified of the original image file.</param>
  544. /// <param name="imageEnhancers">The image enhancers.</param>
  545. /// <returns>Guid.</returns>
  546. /// <exception cref="System.ArgumentNullException">item</exception>
  547. public Guid GetImageCacheTag(IHasImages item, ImageType imageType, string originalImagePath, DateTime dateModified, List<IImageEnhancer> imageEnhancers)
  548. {
  549. if (item == null)
  550. {
  551. throw new ArgumentNullException("item");
  552. }
  553. if (imageEnhancers == null)
  554. {
  555. throw new ArgumentNullException("imageEnhancers");
  556. }
  557. if (string.IsNullOrEmpty(originalImagePath))
  558. {
  559. throw new ArgumentNullException("originalImagePath");
  560. }
  561. // Optimization
  562. if (imageEnhancers.Count == 0)
  563. {
  564. return (originalImagePath + dateModified.Ticks).GetMD5();
  565. }
  566. // Cache name is created with supported enhancers combined with the last config change so we pick up new config changes
  567. var cacheKeys = imageEnhancers.Select(i => i.GetConfigurationCacheKey(item, imageType)).ToList();
  568. cacheKeys.Add(originalImagePath + dateModified.Ticks);
  569. return string.Join("|", cacheKeys.ToArray()).GetMD5();
  570. }
  571. /// <summary>
  572. /// Gets the enhanced image.
  573. /// </summary>
  574. /// <param name="item">The item.</param>
  575. /// <param name="imageType">Type of the image.</param>
  576. /// <param name="imageIndex">Index of the image.</param>
  577. /// <returns>Task{System.String}.</returns>
  578. public async Task<string> GetEnhancedImage(IHasImages item, ImageType imageType, int imageIndex)
  579. {
  580. var enhancers = GetSupportedEnhancers(item, imageType).ToList();
  581. var imageInfo = item.GetImageInfo(imageType, imageIndex);
  582. var imagePath = imageInfo.Path;
  583. var dateModified = imageInfo.DateModified;
  584. var result = await GetEnhancedImage(imagePath, dateModified, item, imageType, imageIndex, enhancers);
  585. return result.Item1;
  586. }
  587. private async Task<Tuple<string, DateTime>> GetEnhancedImage(string originalImagePath, DateTime dateModified, IHasImages item,
  588. ImageType imageType, int imageIndex,
  589. List<IImageEnhancer> enhancers)
  590. {
  591. try
  592. {
  593. // Enhance if we have enhancers
  594. var ehnancedImagePath = await GetEnhancedImageInternal(originalImagePath, dateModified, item, imageType, imageIndex, enhancers).ConfigureAwait(false);
  595. // If the path changed update dateModified
  596. if (!ehnancedImagePath.Equals(originalImagePath, StringComparison.OrdinalIgnoreCase))
  597. {
  598. dateModified = _fileSystem.GetLastWriteTimeUtc(ehnancedImagePath);
  599. return new Tuple<string, DateTime>(ehnancedImagePath, dateModified);
  600. }
  601. }
  602. catch (Exception ex)
  603. {
  604. _logger.Error("Error enhancing image", ex);
  605. }
  606. return new Tuple<string, DateTime>(originalImagePath, dateModified);
  607. }
  608. /// <summary>
  609. /// Runs an image through the image enhancers, caches the result, and returns the cached path
  610. /// </summary>
  611. /// <param name="originalImagePath">The original image path.</param>
  612. /// <param name="dateModified">The date modified of the original image file.</param>
  613. /// <param name="item">The item.</param>
  614. /// <param name="imageType">Type of the image.</param>
  615. /// <param name="imageIndex">Index of the image.</param>
  616. /// <param name="supportedEnhancers">The supported enhancers.</param>
  617. /// <returns>System.String.</returns>
  618. /// <exception cref="System.ArgumentNullException">originalImagePath</exception>
  619. private async Task<string> GetEnhancedImageInternal(string originalImagePath, DateTime dateModified, IHasImages item, ImageType imageType, int imageIndex, List<IImageEnhancer> supportedEnhancers)
  620. {
  621. if (string.IsNullOrEmpty(originalImagePath))
  622. {
  623. throw new ArgumentNullException("originalImagePath");
  624. }
  625. if (item == null)
  626. {
  627. throw new ArgumentNullException("item");
  628. }
  629. var cacheGuid = GetImageCacheTag(item, imageType, originalImagePath, dateModified, supportedEnhancers);
  630. // All enhanced images are saved as png to allow transparency
  631. var enhancedImagePath = GetCachePath(EnhancedImageCachePath, cacheGuid + ".png");
  632. var semaphore = GetLock(enhancedImagePath);
  633. await semaphore.WaitAsync().ConfigureAwait(false);
  634. // Check again in case of contention
  635. if (File.Exists(enhancedImagePath))
  636. {
  637. semaphore.Release();
  638. return enhancedImagePath;
  639. }
  640. try
  641. {
  642. using (var fileStream = _fileSystem.GetFileStream(originalImagePath, FileMode.Open, FileAccess.Read, FileShare.Read, true))
  643. {
  644. // Copy to memory stream to avoid Image locking file
  645. using (var memoryStream = new MemoryStream())
  646. {
  647. await fileStream.CopyToAsync(memoryStream).ConfigureAwait(false);
  648. using (var originalImage = Image.FromStream(memoryStream, true, false))
  649. {
  650. //Pass the image through registered enhancers
  651. using (var newImage = await ExecuteImageEnhancers(supportedEnhancers, originalImage, item, imageType, imageIndex).ConfigureAwait(false))
  652. {
  653. var parentDirectory = Path.GetDirectoryName(enhancedImagePath);
  654. Directory.CreateDirectory(parentDirectory);
  655. //And then save it in the cache
  656. using (var outputStream = _fileSystem.GetFileStream(enhancedImagePath, FileMode.Create, FileAccess.Write, FileShare.Read, false))
  657. {
  658. newImage.Save(System.Drawing.Imaging.ImageFormat.Png, outputStream, 100);
  659. }
  660. }
  661. }
  662. }
  663. }
  664. }
  665. finally
  666. {
  667. semaphore.Release();
  668. }
  669. return enhancedImagePath;
  670. }
  671. /// <summary>
  672. /// Executes the image enhancers.
  673. /// </summary>
  674. /// <param name="imageEnhancers">The image enhancers.</param>
  675. /// <param name="originalImage">The original image.</param>
  676. /// <param name="item">The item.</param>
  677. /// <param name="imageType">Type of the image.</param>
  678. /// <param name="imageIndex">Index of the image.</param>
  679. /// <returns>Task{EnhancedImage}.</returns>
  680. private async Task<Image> ExecuteImageEnhancers(IEnumerable<IImageEnhancer> imageEnhancers, Image originalImage, IHasImages item, ImageType imageType, int imageIndex)
  681. {
  682. var result = originalImage;
  683. // Run the enhancers sequentially in order of priority
  684. foreach (var enhancer in imageEnhancers)
  685. {
  686. var typeName = enhancer.GetType().Name;
  687. try
  688. {
  689. result = await enhancer.EnhanceImageAsync(item, result, imageType, imageIndex).ConfigureAwait(false);
  690. }
  691. catch (Exception ex)
  692. {
  693. _logger.ErrorException("{0} failed enhancing {1}", ex, typeName, item.Name);
  694. throw;
  695. }
  696. }
  697. return result;
  698. }
  699. /// <summary>
  700. /// The _semaphoreLocks
  701. /// </summary>
  702. private readonly ConcurrentDictionary<string, object> _locks = new ConcurrentDictionary<string, object>();
  703. /// <summary>
  704. /// Gets the lock.
  705. /// </summary>
  706. /// <param name="filename">The filename.</param>
  707. /// <returns>System.Object.</returns>
  708. private object GetObjectLock(string filename)
  709. {
  710. return _locks.GetOrAdd(filename, key => new object());
  711. }
  712. /// <summary>
  713. /// The _semaphoreLocks
  714. /// </summary>
  715. private readonly ConcurrentDictionary<string, SemaphoreSlim> _semaphoreLocks = new ConcurrentDictionary<string, SemaphoreSlim>();
  716. /// <summary>
  717. /// Gets the lock.
  718. /// </summary>
  719. /// <param name="filename">The filename.</param>
  720. /// <returns>System.Object.</returns>
  721. private SemaphoreSlim GetLock(string filename)
  722. {
  723. return _semaphoreLocks.GetOrAdd(filename, key => new SemaphoreSlim(1, 1));
  724. }
  725. /// <summary>
  726. /// Gets the cache path.
  727. /// </summary>
  728. /// <param name="path">The path.</param>
  729. /// <param name="uniqueName">Name of the unique.</param>
  730. /// <param name="fileExtension">The file extension.</param>
  731. /// <returns>System.String.</returns>
  732. /// <exception cref="System.ArgumentNullException">
  733. /// path
  734. /// or
  735. /// uniqueName
  736. /// or
  737. /// fileExtension
  738. /// </exception>
  739. public string GetCachePath(string path, string uniqueName, string fileExtension)
  740. {
  741. if (string.IsNullOrEmpty(path))
  742. {
  743. throw new ArgumentNullException("path");
  744. }
  745. if (string.IsNullOrEmpty(uniqueName))
  746. {
  747. throw new ArgumentNullException("uniqueName");
  748. }
  749. if (string.IsNullOrEmpty(fileExtension))
  750. {
  751. throw new ArgumentNullException("fileExtension");
  752. }
  753. var filename = uniqueName.GetMD5() + fileExtension;
  754. return GetCachePath(path, filename);
  755. }
  756. /// <summary>
  757. /// Gets the cache path.
  758. /// </summary>
  759. /// <param name="path">The path.</param>
  760. /// <param name="filename">The filename.</param>
  761. /// <returns>System.String.</returns>
  762. /// <exception cref="System.ArgumentNullException">
  763. /// path
  764. /// or
  765. /// filename
  766. /// </exception>
  767. public string GetCachePath(string path, string filename)
  768. {
  769. if (string.IsNullOrEmpty(path))
  770. {
  771. throw new ArgumentNullException("path");
  772. }
  773. if (string.IsNullOrEmpty(filename))
  774. {
  775. throw new ArgumentNullException("filename");
  776. }
  777. var prefix = filename.Substring(0, 1);
  778. path = Path.Combine(path, prefix);
  779. return Path.Combine(path, filename);
  780. }
  781. public IEnumerable<IImageEnhancer> GetSupportedEnhancers(IHasImages item, ImageType imageType)
  782. {
  783. return ImageEnhancers.Where(i =>
  784. {
  785. try
  786. {
  787. return i.Supports(item, imageType);
  788. }
  789. catch (Exception ex)
  790. {
  791. _logger.ErrorException("Error in image enhancer: {0}", ex, i.GetType().Name);
  792. return false;
  793. }
  794. });
  795. }
  796. public void Dispose()
  797. {
  798. _saveImageSizeTimer.Dispose();
  799. }
  800. }
  801. }