ImageProcessor.cs 26 KB

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