2
0

ImageProcessor.cs 30 KB

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