ImageProcessor.cs 26 KB

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