ImageProcessor.cs 25 KB

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