ImageProcessor.cs 29 KB

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