ImageProcessor.cs 29 KB

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