ImageProcessor.cs 31 KB

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