ImageProcessor.cs 27 KB

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