ImageProcessor.cs 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808
  1. using Emby.Drawing.Common;
  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.Providers;
  8. using MediaBrowser.Model.Drawing;
  9. using MediaBrowser.Model.Entities;
  10. using MediaBrowser.Model.Logging;
  11. using MediaBrowser.Model.Serialization;
  12. using System;
  13. using System.Collections.Concurrent;
  14. using System.Collections.Generic;
  15. using System.Globalization;
  16. using System.IO;
  17. using System.Linq;
  18. using System.Threading;
  19. using System.Threading.Tasks;
  20. namespace Emby.Drawing
  21. {
  22. /// <summary>
  23. /// Class ImageProcessor
  24. /// </summary>
  25. public class ImageProcessor : IImageProcessor, IDisposable
  26. {
  27. /// <summary>
  28. /// The us culture
  29. /// </summary>
  30. protected readonly CultureInfo UsCulture = new CultureInfo("en-US");
  31. /// <summary>
  32. /// The _cached imaged sizes
  33. /// </summary>
  34. private readonly ConcurrentDictionary<Guid, ImageSize> _cachedImagedSizes;
  35. /// <summary>
  36. /// Gets the list of currently registered image processors
  37. /// Image processors are specialized metadata providers that run after the normal ones
  38. /// </summary>
  39. /// <value>The image enhancers.</value>
  40. public IEnumerable<IImageEnhancer> ImageEnhancers { get; private set; }
  41. /// <summary>
  42. /// The _logger
  43. /// </summary>
  44. private readonly ILogger _logger;
  45. private readonly IFileSystem _fileSystem;
  46. private readonly IJsonSerializer _jsonSerializer;
  47. private readonly IServerApplicationPaths _appPaths;
  48. private readonly IImageEncoder _imageEncoder;
  49. private readonly SemaphoreSlim _imageProcessingSemaphore;
  50. public ImageProcessor(ILogger logger,
  51. IServerApplicationPaths appPaths,
  52. IFileSystem fileSystem,
  53. IJsonSerializer jsonSerializer,
  54. IImageEncoder imageEncoder)
  55. {
  56. _logger = logger;
  57. _fileSystem = fileSystem;
  58. _jsonSerializer = jsonSerializer;
  59. _imageEncoder = imageEncoder;
  60. _appPaths = appPaths;
  61. ImageEnhancers = new List<IImageEnhancer>();
  62. _saveImageSizeTimer = new Timer(SaveImageSizeCallback, null, Timeout.Infinite, Timeout.Infinite);
  63. Dictionary<Guid, ImageSize> sizeDictionary;
  64. try
  65. {
  66. sizeDictionary = jsonSerializer.DeserializeFromFile<Dictionary<Guid, ImageSize>>(ImageSizeFile) ??
  67. new Dictionary<Guid, ImageSize>();
  68. }
  69. catch (FileNotFoundException)
  70. {
  71. // No biggie
  72. sizeDictionary = new Dictionary<Guid, ImageSize>();
  73. }
  74. catch (DirectoryNotFoundException)
  75. {
  76. // No biggie
  77. sizeDictionary = new Dictionary<Guid, ImageSize>();
  78. }
  79. catch (Exception ex)
  80. {
  81. logger.ErrorException("Error parsing image size cache file", ex);
  82. sizeDictionary = new Dictionary<Guid, ImageSize>();
  83. }
  84. _cachedImagedSizes = new ConcurrentDictionary<Guid, ImageSize>(sizeDictionary);
  85. var count = Environment.ProcessorCount;
  86. _imageProcessingSemaphore = new SemaphoreSlim(count, count);
  87. }
  88. public string[] SupportedInputFormats
  89. {
  90. get
  91. {
  92. return _imageEncoder.SupportedInputFormats;
  93. }
  94. }
  95. private string ResizedImageCachePath
  96. {
  97. get
  98. {
  99. return Path.Combine(_appPaths.ImageCachePath, "resized-images");
  100. }
  101. }
  102. private string EnhancedImageCachePath
  103. {
  104. get
  105. {
  106. return Path.Combine(_appPaths.ImageCachePath, "enhanced-images");
  107. }
  108. }
  109. private string CroppedWhitespaceImageCachePath
  110. {
  111. get
  112. {
  113. return Path.Combine(_appPaths.ImageCachePath, "cropped-images");
  114. }
  115. }
  116. public void AddParts(IEnumerable<IImageEnhancer> enhancers)
  117. {
  118. ImageEnhancers = enhancers.ToArray();
  119. }
  120. public async Task ProcessImage(ImageProcessingOptions options, Stream toStream)
  121. {
  122. var file = await ProcessImage(options).ConfigureAwait(false);
  123. using (var fileStream = _fileSystem.GetFileStream(file, FileMode.Open, FileAccess.Read, FileShare.Read, true))
  124. {
  125. await fileStream.CopyToAsync(toStream).ConfigureAwait(false);
  126. }
  127. }
  128. public ImageFormat[] GetSupportedImageOutputFormats()
  129. {
  130. return _imageEncoder.SupportedOutputFormats;
  131. }
  132. public async Task<string> ProcessImage(ImageProcessingOptions options)
  133. {
  134. if (options == null)
  135. {
  136. throw new ArgumentNullException("options");
  137. }
  138. var originalImagePath = options.Image.Path;
  139. if (options.HasDefaultOptions(originalImagePath) && options.Enhancers.Count == 0 && !options.CropWhiteSpace)
  140. {
  141. // Just spit out the original file if all the options are default
  142. return originalImagePath;
  143. }
  144. var dateModified = options.Image.DateModified;
  145. if (options.CropWhiteSpace)
  146. {
  147. var tuple = await GetWhitespaceCroppedImage(originalImagePath, dateModified).ConfigureAwait(false);
  148. originalImagePath = tuple.Item1;
  149. dateModified = tuple.Item2;
  150. }
  151. if (options.Enhancers.Count > 0)
  152. {
  153. var tuple = await GetEnhancedImage(new ItemImageInfo
  154. {
  155. DateModified = dateModified,
  156. Type = options.Image.Type,
  157. Path = originalImagePath
  158. }, options.Item, options.ImageIndex, options.Enhancers).ConfigureAwait(false);
  159. originalImagePath = tuple.Item1;
  160. dateModified = tuple.Item2;
  161. }
  162. var originalImageSize = GetImageSize(originalImagePath, dateModified);
  163. // Determine the output size based on incoming parameters
  164. var newSize = DrawingUtils.Resize(originalImageSize, options.Width, options.Height, options.MaxWidth, options.MaxHeight);
  165. if (options.HasDefaultOptionsWithoutSize(originalImagePath) && newSize.Equals(originalImageSize) && options.Enhancers.Count == 0)
  166. {
  167. // Just spit out the original file if the new size equals the old
  168. return originalImagePath;
  169. }
  170. var quality = options.Quality ?? 90;
  171. var outputFormat = GetOutputFormat(options.OutputFormat);
  172. var cacheFilePath = GetCacheFilePath(originalImagePath, newSize, quality, dateModified, outputFormat, options.AddPlayedIndicator, options.PercentPlayed, options.UnplayedCount, options.BackgroundColor);
  173. var semaphore = GetLock(cacheFilePath);
  174. await semaphore.WaitAsync().ConfigureAwait(false);
  175. var imageProcessingLockTaken = false;
  176. try
  177. {
  178. CheckDisposed();
  179. if (!File.Exists(cacheFilePath))
  180. {
  181. var newWidth = Convert.ToInt32(newSize.Width);
  182. var newHeight = Convert.ToInt32(newSize.Height);
  183. Directory.CreateDirectory(Path.GetDirectoryName(cacheFilePath));
  184. await _imageProcessingSemaphore.WaitAsync().ConfigureAwait(false);
  185. imageProcessingLockTaken = true;
  186. _imageEncoder.EncodeImage(originalImagePath, cacheFilePath, newWidth, newHeight, quality, options);
  187. }
  188. }
  189. finally
  190. {
  191. if (imageProcessingLockTaken)
  192. {
  193. _imageProcessingSemaphore.Release();
  194. }
  195. semaphore.Release();
  196. }
  197. return cacheFilePath;
  198. }
  199. private ImageFormat GetOutputFormat(ImageFormat requestedFormat)
  200. {
  201. if (requestedFormat == ImageFormat.Webp && !_imageEncoder.SupportedOutputFormats.Contains(ImageFormat.Webp))
  202. {
  203. return ImageFormat.Png;
  204. }
  205. return requestedFormat;
  206. }
  207. /// <summary>
  208. /// Crops whitespace from an image, caches the result, and returns the cached path
  209. /// </summary>
  210. private async Task<Tuple<string, DateTime>> GetWhitespaceCroppedImage(string originalImagePath, DateTime dateModified)
  211. {
  212. var name = originalImagePath;
  213. name += "datemodified=" + dateModified.Ticks;
  214. var croppedImagePath = GetCachePath(CroppedWhitespaceImageCachePath, name, Path.GetExtension(originalImagePath));
  215. var semaphore = GetLock(croppedImagePath);
  216. await semaphore.WaitAsync().ConfigureAwait(false);
  217. // Check again in case of contention
  218. if (File.Exists(croppedImagePath))
  219. {
  220. semaphore.Release();
  221. return GetResult(croppedImagePath);
  222. }
  223. var imageProcessingLockTaken = false;
  224. try
  225. {
  226. Directory.CreateDirectory(Path.GetDirectoryName(croppedImagePath));
  227. await _imageProcessingSemaphore.WaitAsync().ConfigureAwait(false);
  228. imageProcessingLockTaken = true;
  229. _imageEncoder.CropWhiteSpace(originalImagePath, croppedImagePath);
  230. }
  231. catch (Exception ex)
  232. {
  233. // We have to have a catch-all here because some of the .net image methods throw a plain old Exception
  234. _logger.ErrorException("Error cropping image {0}", ex, originalImagePath);
  235. return new Tuple<string, DateTime>(originalImagePath, dateModified);
  236. }
  237. finally
  238. {
  239. if (imageProcessingLockTaken)
  240. {
  241. _imageProcessingSemaphore.Release();
  242. }
  243. semaphore.Release();
  244. }
  245. return GetResult(croppedImagePath);
  246. }
  247. private Tuple<string, DateTime> GetResult(string path)
  248. {
  249. return new Tuple<string, DateTime>(path, _fileSystem.GetLastWriteTimeUtc(path));
  250. }
  251. /// <summary>
  252. /// Increment this when there's a change requiring caches to be invalidated
  253. /// </summary>
  254. private const string Version = "3";
  255. /// <summary>
  256. /// Gets the cache file path based on a set of parameters
  257. /// </summary>
  258. private string GetCacheFilePath(string originalPath, ImageSize outputSize, int quality, DateTime dateModified, ImageFormat format, bool addPlayedIndicator, double percentPlayed, int? unwatchedCount, string backgroundColor)
  259. {
  260. var filename = originalPath;
  261. filename += "width=" + outputSize.Width;
  262. filename += "height=" + outputSize.Height;
  263. filename += "quality=" + quality;
  264. filename += "datemodified=" + dateModified.Ticks;
  265. filename += "f=" + format;
  266. if (addPlayedIndicator)
  267. {
  268. filename += "pl=true";
  269. }
  270. if (percentPlayed > 0)
  271. {
  272. filename += "p=" + percentPlayed;
  273. }
  274. if (unwatchedCount.HasValue)
  275. {
  276. filename += "p=" + unwatchedCount.Value;
  277. }
  278. if (!string.IsNullOrEmpty(backgroundColor))
  279. {
  280. filename += "b=" + backgroundColor;
  281. }
  282. filename += "v=" + Version;
  283. return GetCachePath(ResizedImageCachePath, filename, "." + format.ToString().ToLower());
  284. }
  285. /// <summary>
  286. /// Gets the size of the image.
  287. /// </summary>
  288. /// <param name="path">The path.</param>
  289. /// <returns>ImageSize.</returns>
  290. public ImageSize GetImageSize(string path)
  291. {
  292. return GetImageSize(path, File.GetLastWriteTimeUtc(path));
  293. }
  294. public ImageSize GetImageSize(ItemImageInfo info)
  295. {
  296. return GetImageSize(info.Path, info.DateModified);
  297. }
  298. /// <summary>
  299. /// Gets the size of the image.
  300. /// </summary>
  301. /// <param name="path">The path.</param>
  302. /// <param name="imageDateModified">The image date modified.</param>
  303. /// <returns>ImageSize.</returns>
  304. /// <exception cref="System.ArgumentNullException">path</exception>
  305. private ImageSize GetImageSize(string path, DateTime imageDateModified)
  306. {
  307. if (string.IsNullOrEmpty(path))
  308. {
  309. throw new ArgumentNullException("path");
  310. }
  311. var name = path + "datemodified=" + imageDateModified.Ticks;
  312. ImageSize size;
  313. var cacheHash = name.GetMD5();
  314. if (!_cachedImagedSizes.TryGetValue(cacheHash, out size))
  315. {
  316. size = GetImageSizeInternal(path);
  317. _cachedImagedSizes.AddOrUpdate(cacheHash, size, (keyName, oldValue) => size);
  318. }
  319. return size;
  320. }
  321. /// <summary>
  322. /// Gets the image size internal.
  323. /// </summary>
  324. /// <param name="path">The path.</param>
  325. /// <returns>ImageSize.</returns>
  326. private ImageSize GetImageSizeInternal(string path)
  327. {
  328. ImageSize size;
  329. try
  330. {
  331. size = ImageHeader.GetDimensions(path, _logger, _fileSystem);
  332. }
  333. catch
  334. {
  335. _logger.Info("Failed to read image header for {0}. Doing it the slow way.", path);
  336. CheckDisposed();
  337. size = _imageEncoder.GetImageSize(path);
  338. }
  339. StartSaveImageSizeTimer();
  340. return size;
  341. }
  342. private readonly Timer _saveImageSizeTimer;
  343. private const int SaveImageSizeTimeout = 5000;
  344. private readonly object _saveImageSizeLock = new object();
  345. private void StartSaveImageSizeTimer()
  346. {
  347. _saveImageSizeTimer.Change(SaveImageSizeTimeout, Timeout.Infinite);
  348. }
  349. private void SaveImageSizeCallback(object state)
  350. {
  351. lock (_saveImageSizeLock)
  352. {
  353. try
  354. {
  355. var path = ImageSizeFile;
  356. Directory.CreateDirectory(Path.GetDirectoryName(path));
  357. _jsonSerializer.SerializeToFile(_cachedImagedSizes, path);
  358. }
  359. catch (Exception ex)
  360. {
  361. _logger.ErrorException("Error saving image size file", ex);
  362. }
  363. }
  364. }
  365. private string ImageSizeFile
  366. {
  367. get
  368. {
  369. return Path.Combine(_appPaths.DataPath, "imagesizes.json");
  370. }
  371. }
  372. /// <summary>
  373. /// Gets the image cache tag.
  374. /// </summary>
  375. /// <param name="item">The item.</param>
  376. /// <param name="image">The image.</param>
  377. /// <returns>Guid.</returns>
  378. /// <exception cref="System.ArgumentNullException">item</exception>
  379. public string GetImageCacheTag(IHasImages item, ItemImageInfo image)
  380. {
  381. if (item == null)
  382. {
  383. throw new ArgumentNullException("item");
  384. }
  385. if (image == null)
  386. {
  387. throw new ArgumentNullException("image");
  388. }
  389. var supportedEnhancers = GetSupportedEnhancers(item, image.Type);
  390. return GetImageCacheTag(item, image, supportedEnhancers.ToList());
  391. }
  392. /// <summary>
  393. /// Gets the image cache tag.
  394. /// </summary>
  395. /// <param name="item">The item.</param>
  396. /// <param name="image">The image.</param>
  397. /// <param name="imageEnhancers">The image enhancers.</param>
  398. /// <returns>Guid.</returns>
  399. /// <exception cref="System.ArgumentNullException">item</exception>
  400. public string GetImageCacheTag(IHasImages item, ItemImageInfo image, List<IImageEnhancer> imageEnhancers)
  401. {
  402. if (item == null)
  403. {
  404. throw new ArgumentNullException("item");
  405. }
  406. if (imageEnhancers == null)
  407. {
  408. throw new ArgumentNullException("imageEnhancers");
  409. }
  410. if (image == null)
  411. {
  412. throw new ArgumentNullException("image");
  413. }
  414. var originalImagePath = image.Path;
  415. var dateModified = image.DateModified;
  416. var imageType = image.Type;
  417. // Optimization
  418. if (imageEnhancers.Count == 0)
  419. {
  420. return (originalImagePath + dateModified.Ticks).GetMD5().ToString("N");
  421. }
  422. // Cache name is created with supported enhancers combined with the last config change so we pick up new config changes
  423. var cacheKeys = imageEnhancers.Select(i => i.GetConfigurationCacheKey(item, imageType)).ToList();
  424. cacheKeys.Add(originalImagePath + dateModified.Ticks);
  425. return string.Join("|", cacheKeys.ToArray()).GetMD5().ToString("N");
  426. }
  427. /// <summary>
  428. /// Gets the enhanced image.
  429. /// </summary>
  430. /// <param name="item">The item.</param>
  431. /// <param name="imageType">Type of the image.</param>
  432. /// <param name="imageIndex">Index of the image.</param>
  433. /// <returns>Task{System.String}.</returns>
  434. public async Task<string> GetEnhancedImage(IHasImages item, ImageType imageType, int imageIndex)
  435. {
  436. var enhancers = GetSupportedEnhancers(item, imageType).ToList();
  437. var imageInfo = item.GetImageInfo(imageType, imageIndex);
  438. var result = await GetEnhancedImage(imageInfo, item, imageIndex, enhancers);
  439. return result.Item1;
  440. }
  441. private async Task<Tuple<string, DateTime>> GetEnhancedImage(ItemImageInfo image,
  442. IHasImages item,
  443. int imageIndex,
  444. List<IImageEnhancer> enhancers)
  445. {
  446. var originalImagePath = image.Path;
  447. var dateModified = image.DateModified;
  448. var imageType = image.Type;
  449. try
  450. {
  451. var cacheGuid = GetImageCacheTag(item, image, enhancers);
  452. // Enhance if we have enhancers
  453. var ehnancedImagePath = await GetEnhancedImageInternal(originalImagePath, item, imageType, imageIndex, enhancers, cacheGuid).ConfigureAwait(false);
  454. // If the path changed update dateModified
  455. if (!ehnancedImagePath.Equals(originalImagePath, StringComparison.OrdinalIgnoreCase))
  456. {
  457. return GetResult(ehnancedImagePath);
  458. }
  459. }
  460. catch (Exception ex)
  461. {
  462. _logger.Error("Error enhancing image", ex);
  463. }
  464. return new Tuple<string, DateTime>(originalImagePath, dateModified);
  465. }
  466. /// <summary>
  467. /// Gets the enhanced image internal.
  468. /// </summary>
  469. /// <param name="originalImagePath">The original image path.</param>
  470. /// <param name="item">The item.</param>
  471. /// <param name="imageType">Type of the image.</param>
  472. /// <param name="imageIndex">Index of the image.</param>
  473. /// <param name="supportedEnhancers">The supported enhancers.</param>
  474. /// <param name="cacheGuid">The cache unique identifier.</param>
  475. /// <returns>Task&lt;System.String&gt;.</returns>
  476. /// <exception cref="ArgumentNullException">
  477. /// originalImagePath
  478. /// or
  479. /// item
  480. /// </exception>
  481. private async Task<string> GetEnhancedImageInternal(string originalImagePath,
  482. IHasImages item,
  483. ImageType imageType,
  484. int imageIndex,
  485. IEnumerable<IImageEnhancer> supportedEnhancers,
  486. string cacheGuid)
  487. {
  488. if (string.IsNullOrEmpty(originalImagePath))
  489. {
  490. throw new ArgumentNullException("originalImagePath");
  491. }
  492. if (item == null)
  493. {
  494. throw new ArgumentNullException("item");
  495. }
  496. // All enhanced images are saved as png to allow transparency
  497. var enhancedImagePath = GetCachePath(EnhancedImageCachePath, cacheGuid + ".png");
  498. var semaphore = GetLock(enhancedImagePath);
  499. await semaphore.WaitAsync().ConfigureAwait(false);
  500. // Check again in case of contention
  501. if (File.Exists(enhancedImagePath))
  502. {
  503. semaphore.Release();
  504. return enhancedImagePath;
  505. }
  506. var imageProcessingLockTaken = false;
  507. try
  508. {
  509. Directory.CreateDirectory(Path.GetDirectoryName(enhancedImagePath));
  510. await _imageProcessingSemaphore.WaitAsync().ConfigureAwait(false);
  511. imageProcessingLockTaken = true;
  512. await ExecuteImageEnhancers(supportedEnhancers, originalImagePath, enhancedImagePath, item, imageType, imageIndex).ConfigureAwait(false);
  513. }
  514. finally
  515. {
  516. if (imageProcessingLockTaken)
  517. {
  518. _imageProcessingSemaphore.Release();
  519. }
  520. semaphore.Release();
  521. }
  522. return enhancedImagePath;
  523. }
  524. /// <summary>
  525. /// Executes the image enhancers.
  526. /// </summary>
  527. /// <param name="imageEnhancers">The image enhancers.</param>
  528. /// <param name="inputPath">The input path.</param>
  529. /// <param name="outputPath">The output path.</param>
  530. /// <param name="item">The item.</param>
  531. /// <param name="imageType">Type of the image.</param>
  532. /// <param name="imageIndex">Index of the image.</param>
  533. /// <returns>Task{EnhancedImage}.</returns>
  534. private async Task ExecuteImageEnhancers(IEnumerable<IImageEnhancer> imageEnhancers, string inputPath, string outputPath, IHasImages item, ImageType imageType, int imageIndex)
  535. {
  536. // Run the enhancers sequentially in order of priority
  537. foreach (var enhancer in imageEnhancers)
  538. {
  539. var typeName = enhancer.GetType().Name;
  540. try
  541. {
  542. await enhancer.EnhanceImageAsync(item, inputPath, outputPath, imageType, imageIndex).ConfigureAwait(false);
  543. }
  544. catch (Exception ex)
  545. {
  546. _logger.ErrorException("{0} failed enhancing {1}", ex, typeName, item.Name);
  547. throw;
  548. }
  549. // Feed the output into the next enhancer as input
  550. inputPath = outputPath;
  551. }
  552. }
  553. /// <summary>
  554. /// The _semaphoreLocks
  555. /// </summary>
  556. private readonly ConcurrentDictionary<string, SemaphoreSlim> _semaphoreLocks = new ConcurrentDictionary<string, SemaphoreSlim>();
  557. /// <summary>
  558. /// Gets the lock.
  559. /// </summary>
  560. /// <param name="filename">The filename.</param>
  561. /// <returns>System.Object.</returns>
  562. private SemaphoreSlim GetLock(string filename)
  563. {
  564. return _semaphoreLocks.GetOrAdd(filename, key => new SemaphoreSlim(1, 1));
  565. }
  566. /// <summary>
  567. /// Gets the cache path.
  568. /// </summary>
  569. /// <param name="path">The path.</param>
  570. /// <param name="uniqueName">Name of the unique.</param>
  571. /// <param name="fileExtension">The file extension.</param>
  572. /// <returns>System.String.</returns>
  573. /// <exception cref="System.ArgumentNullException">
  574. /// path
  575. /// or
  576. /// uniqueName
  577. /// or
  578. /// fileExtension
  579. /// </exception>
  580. public string GetCachePath(string path, string uniqueName, string fileExtension)
  581. {
  582. if (string.IsNullOrEmpty(path))
  583. {
  584. throw new ArgumentNullException("path");
  585. }
  586. if (string.IsNullOrEmpty(uniqueName))
  587. {
  588. throw new ArgumentNullException("uniqueName");
  589. }
  590. if (string.IsNullOrEmpty(fileExtension))
  591. {
  592. throw new ArgumentNullException("fileExtension");
  593. }
  594. var filename = uniqueName.GetMD5() + fileExtension;
  595. return GetCachePath(path, filename);
  596. }
  597. /// <summary>
  598. /// Gets the cache path.
  599. /// </summary>
  600. /// <param name="path">The path.</param>
  601. /// <param name="filename">The filename.</param>
  602. /// <returns>System.String.</returns>
  603. /// <exception cref="System.ArgumentNullException">
  604. /// path
  605. /// or
  606. /// filename
  607. /// </exception>
  608. public string GetCachePath(string path, string filename)
  609. {
  610. if (string.IsNullOrEmpty(path))
  611. {
  612. throw new ArgumentNullException("path");
  613. }
  614. if (string.IsNullOrEmpty(filename))
  615. {
  616. throw new ArgumentNullException("filename");
  617. }
  618. var prefix = filename.Substring(0, 1);
  619. path = Path.Combine(path, prefix);
  620. return Path.Combine(path, filename);
  621. }
  622. public async Task CreateImageCollage(ImageCollageOptions options)
  623. {
  624. await _imageProcessingSemaphore.WaitAsync().ConfigureAwait(false);
  625. try
  626. {
  627. _imageEncoder.CreateImageCollage(options);
  628. }
  629. finally
  630. {
  631. _imageProcessingSemaphore.Release();
  632. }
  633. }
  634. public IEnumerable<IImageEnhancer> GetSupportedEnhancers(IHasImages item, ImageType imageType)
  635. {
  636. return ImageEnhancers.Where(i =>
  637. {
  638. try
  639. {
  640. return i.Supports(item, imageType);
  641. }
  642. catch (Exception ex)
  643. {
  644. _logger.ErrorException("Error in image enhancer: {0}", ex, i.GetType().Name);
  645. return false;
  646. }
  647. });
  648. }
  649. private bool _disposed;
  650. public void Dispose()
  651. {
  652. _disposed = true;
  653. _imageEncoder.Dispose();
  654. _saveImageSizeTimer.Dispose();
  655. }
  656. private void CheckDisposed()
  657. {
  658. if (_disposed)
  659. {
  660. throw new ObjectDisposedException(GetType().Name);
  661. }
  662. }
  663. }
  664. }