ImageProcessor.cs 32 KB

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