ImageProcessor.cs 31 KB

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