ImageManager.cs 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598
  1. using MediaBrowser.Common.Extensions;
  2. using MediaBrowser.Common.IO;
  3. using MediaBrowser.Common.Kernel;
  4. using MediaBrowser.Controller.Entities;
  5. using MediaBrowser.Controller.Entities.TV;
  6. using MediaBrowser.Controller.Providers;
  7. using MediaBrowser.Model.Drawing;
  8. using MediaBrowser.Model.Entities;
  9. using System;
  10. using System.Collections.Concurrent;
  11. using System.Collections.Generic;
  12. using System.Drawing;
  13. using System.Drawing.Drawing2D;
  14. using System.Drawing.Imaging;
  15. using System.IO;
  16. using System.Linq;
  17. using System.Threading.Tasks;
  18. namespace MediaBrowser.Controller.Drawing
  19. {
  20. /// <summary>
  21. /// Class ImageManager
  22. /// </summary>
  23. public class ImageManager : BaseManager<Kernel>
  24. {
  25. /// <summary>
  26. /// Gets the image size cache.
  27. /// </summary>
  28. /// <value>The image size cache.</value>
  29. private FileSystemRepository ImageSizeCache { get; set; }
  30. /// <summary>
  31. /// Gets or sets the resized image cache.
  32. /// </summary>
  33. /// <value>The resized image cache.</value>
  34. private FileSystemRepository ResizedImageCache { get; set; }
  35. /// <summary>
  36. /// Gets the cropped image cache.
  37. /// </summary>
  38. /// <value>The cropped image cache.</value>
  39. private FileSystemRepository CroppedImageCache { get; set; }
  40. /// <summary>
  41. /// Gets the cropped image cache.
  42. /// </summary>
  43. /// <value>The cropped image cache.</value>
  44. private FileSystemRepository EnhancedImageCache { get; set; }
  45. /// <summary>
  46. /// The cached imaged sizes
  47. /// </summary>
  48. private readonly ConcurrentDictionary<string, Task<ImageSize>> _cachedImagedSizes = new ConcurrentDictionary<string, Task<ImageSize>>();
  49. /// <summary>
  50. /// Initializes a new instance of the <see cref="ImageManager" /> class.
  51. /// </summary>
  52. /// <param name="kernel">The kernel.</param>
  53. public ImageManager(Kernel kernel)
  54. : base(kernel)
  55. {
  56. ImageSizeCache = new FileSystemRepository(Path.Combine(Kernel.ApplicationPaths.ImageCachePath, "image-sizes"));
  57. ResizedImageCache = new FileSystemRepository(Path.Combine(Kernel.ApplicationPaths.ImageCachePath, "resized-images"));
  58. CroppedImageCache = new FileSystemRepository(Path.Combine(Kernel.ApplicationPaths.ImageCachePath, "cropped-images"));
  59. EnhancedImageCache = new FileSystemRepository(Path.Combine(Kernel.ApplicationPaths.ImageCachePath, "enhanced-images"));
  60. }
  61. /// <summary>
  62. /// Processes an image by resizing to target dimensions
  63. /// </summary>
  64. /// <param name="entity">The entity that owns the image</param>
  65. /// <param name="imageType">The image type</param>
  66. /// <param name="imageIndex">The image index (currently only used with backdrops)</param>
  67. /// <param name="cropWhitespace">if set to <c>true</c> [crop whitespace].</param>
  68. /// <param name="dateModified">The last date modified of the original image file</param>
  69. /// <param name="toStream">The stream to save the new image to</param>
  70. /// <param name="width">Use if a fixed width is required. Aspect ratio will be preserved.</param>
  71. /// <param name="height">Use if a fixed height is required. Aspect ratio will be preserved.</param>
  72. /// <param name="maxWidth">Use if a max width is required. Aspect ratio will be preserved.</param>
  73. /// <param name="maxHeight">Use if a max height is required. Aspect ratio will be preserved.</param>
  74. /// <param name="quality">Quality level, from 0-100. Currently only applies to JPG. The default value should suffice.</param>
  75. /// <returns>Task.</returns>
  76. /// <exception cref="System.ArgumentNullException">entity</exception>
  77. public async Task ProcessImage(BaseItem entity, ImageType imageType, int imageIndex, bool cropWhitespace, DateTime dateModified, Stream toStream, int? width, int? height, int? maxWidth, int? maxHeight, int? quality)
  78. {
  79. if (entity == null)
  80. {
  81. throw new ArgumentNullException("entity");
  82. }
  83. if (toStream == null)
  84. {
  85. throw new ArgumentNullException("toStream");
  86. }
  87. var originalImagePath = GetImagePath(entity, imageType, imageIndex);
  88. if (cropWhitespace)
  89. {
  90. try
  91. {
  92. originalImagePath = GetCroppedImage(originalImagePath, dateModified);
  93. }
  94. catch (Exception ex)
  95. {
  96. // We have to have a catch-all here because some of the .net image methods throw a plain old Exception
  97. Logger.ErrorException("Error cropping image", ex);
  98. }
  99. }
  100. try
  101. {
  102. // Enhance if we have enhancers
  103. var ehnancedImagePath = await GetEnhancedImage(originalImagePath, dateModified, entity, imageType, imageIndex).ConfigureAwait(false);
  104. // If the path changed update dateModified
  105. if (!ehnancedImagePath.Equals(originalImagePath, StringComparison.OrdinalIgnoreCase))
  106. {
  107. dateModified = File.GetLastWriteTimeUtc(ehnancedImagePath);
  108. originalImagePath = ehnancedImagePath;
  109. }
  110. }
  111. catch
  112. {
  113. Logger.Error("Error enhancing image");
  114. }
  115. var originalImageSize = await GetImageSize(originalImagePath, dateModified).ConfigureAwait(false);
  116. // Determine the output size based on incoming parameters
  117. var newSize = DrawingUtils.Resize(originalImageSize, width, height, maxWidth, maxHeight);
  118. if (!quality.HasValue)
  119. {
  120. quality = 90;
  121. }
  122. var cacheFilePath = GetCacheFilePath(originalImagePath, newSize, quality.Value, dateModified);
  123. // Grab the cache file if it already exists
  124. try
  125. {
  126. using (var fileStream = new FileStream(cacheFilePath, FileMode.Open, FileAccess.Read, FileShare.Read, StreamDefaults.DefaultFileStreamBufferSize, FileOptions.Asynchronous))
  127. {
  128. await fileStream.CopyToAsync(toStream).ConfigureAwait(false);
  129. }
  130. return;
  131. }
  132. catch (FileNotFoundException)
  133. {
  134. // Cache file doesn't exist. No biggie.
  135. }
  136. using (var fileStream = File.OpenRead(originalImagePath))
  137. {
  138. using (var originalImage = Bitmap.FromStream(fileStream, true, false))
  139. {
  140. var newWidth = Convert.ToInt32(newSize.Width);
  141. var newHeight = Convert.ToInt32(newSize.Height);
  142. // Graphics.FromImage will throw an exception if the PixelFormat is Indexed, so we need to handle that here
  143. var thumbnail = originalImage.PixelFormat.HasFlag(PixelFormat.Indexed) ? new Bitmap(originalImage, newWidth, newHeight) : new Bitmap(newWidth, newHeight, originalImage.PixelFormat);
  144. // Preserve the original resolution
  145. thumbnail.SetResolution(originalImage.HorizontalResolution, originalImage.VerticalResolution);
  146. var thumbnailGraph = Graphics.FromImage(thumbnail);
  147. thumbnailGraph.CompositingQuality = CompositingQuality.HighQuality;
  148. thumbnailGraph.SmoothingMode = SmoothingMode.HighQuality;
  149. thumbnailGraph.InterpolationMode = InterpolationMode.HighQualityBicubic;
  150. thumbnailGraph.PixelOffsetMode = PixelOffsetMode.HighQuality;
  151. thumbnailGraph.CompositingMode = CompositingMode.SourceOver;
  152. thumbnailGraph.DrawImage(originalImage, 0, 0, newWidth, newHeight);
  153. var outputFormat = originalImage.RawFormat;
  154. using (var memoryStream = new MemoryStream { })
  155. {
  156. // Save to the memory stream
  157. thumbnail.Save(outputFormat, memoryStream, quality.Value);
  158. var bytes = memoryStream.ToArray();
  159. var outputTask = Task.Run(async () => await toStream.WriteAsync(bytes, 0, bytes.Length));
  160. // Save to the cache location
  161. using (var cacheFileStream = new FileStream(cacheFilePath, FileMode.Create, FileAccess.Write, FileShare.Read, StreamDefaults.DefaultFileStreamBufferSize, FileOptions.Asynchronous))
  162. {
  163. // Save to the filestream
  164. await cacheFileStream.WriteAsync(bytes, 0, bytes.Length);
  165. }
  166. await outputTask.ConfigureAwait(false);
  167. }
  168. thumbnailGraph.Dispose();
  169. thumbnail.Dispose();
  170. }
  171. }
  172. }
  173. /// <summary>
  174. /// Gets the cache file path based on a set of parameters
  175. /// </summary>
  176. /// <param name="originalPath">The path to the original image file</param>
  177. /// <param name="outputSize">The size to output the image in</param>
  178. /// <param name="quality">Quality level, from 0-100. Currently only applies to JPG. The default value should suffice.</param>
  179. /// <param name="dateModified">The last modified date of the image</param>
  180. /// <returns>System.String.</returns>
  181. private string GetCacheFilePath(string originalPath, ImageSize outputSize, int quality, DateTime dateModified)
  182. {
  183. var filename = originalPath;
  184. filename += "width=" + outputSize.Width;
  185. filename += "height=" + outputSize.Height;
  186. filename += "quality=" + quality;
  187. filename += "datemodified=" + dateModified.Ticks;
  188. return ResizedImageCache.GetResourcePath(filename, Path.GetExtension(originalPath));
  189. }
  190. /// <summary>
  191. /// Gets image dimensions
  192. /// </summary>
  193. /// <param name="imagePath">The image path.</param>
  194. /// <param name="dateModified">The date modified.</param>
  195. /// <returns>Task{ImageSize}.</returns>
  196. /// <exception cref="System.ArgumentNullException">imagePath</exception>
  197. public Task<ImageSize> GetImageSize(string imagePath, DateTime dateModified)
  198. {
  199. if (string.IsNullOrEmpty(imagePath))
  200. {
  201. throw new ArgumentNullException("imagePath");
  202. }
  203. var name = imagePath + "datemodified=" + dateModified.Ticks;
  204. return _cachedImagedSizes.GetOrAdd(name, keyName => GetImageSizeTask(keyName, imagePath));
  205. }
  206. /// <summary>
  207. /// Gets cached image dimensions, or results null if non-existant
  208. /// </summary>
  209. /// <param name="keyName">Name of the key.</param>
  210. /// <param name="imagePath">The image path.</param>
  211. /// <returns>Task{ImageSize}.</returns>
  212. private Task<ImageSize> GetImageSizeTask(string keyName, string imagePath)
  213. {
  214. return Task.Run(() => GetImageSize(keyName, imagePath));
  215. }
  216. /// <summary>
  217. /// Gets the size of the image.
  218. /// </summary>
  219. /// <param name="keyName">Name of the key.</param>
  220. /// <param name="imagePath">The image path.</param>
  221. /// <returns>ImageSize.</returns>
  222. private ImageSize GetImageSize(string keyName, string imagePath)
  223. {
  224. // Now check the file system cache
  225. var fullCachePath = ImageSizeCache.GetResourcePath(keyName, ".pb");
  226. try
  227. {
  228. var result = Kernel.ProtobufSerializer.DeserializeFromFile<int[]>(fullCachePath);
  229. return new ImageSize { Width = result[0], Height = result[1] };
  230. }
  231. catch (FileNotFoundException)
  232. {
  233. // Cache file doesn't exist no biggie
  234. }
  235. var size = ImageHeader.GetDimensions(imagePath);
  236. var imageSize = new ImageSize { Width = size.Width, Height = size.Height };
  237. // Update the file system cache
  238. CacheImageSize(fullCachePath, size.Width, size.Height);
  239. return imageSize;
  240. }
  241. /// <summary>
  242. /// Caches image dimensions
  243. /// </summary>
  244. /// <param name="cachePath">The cache path.</param>
  245. /// <param name="width">The width.</param>
  246. /// <param name="height">The height.</param>
  247. private void CacheImageSize(string cachePath, int width, int height)
  248. {
  249. var output = new[] { width, height };
  250. Kernel.ProtobufSerializer.SerializeToFile(output, cachePath);
  251. }
  252. /// <summary>
  253. /// Gets the image path.
  254. /// </summary>
  255. /// <param name="item">The item.</param>
  256. /// <param name="imageType">Type of the image.</param>
  257. /// <param name="imageIndex">Index of the image.</param>
  258. /// <returns>System.String.</returns>
  259. /// <exception cref="System.ArgumentNullException">item</exception>
  260. /// <exception cref="System.InvalidOperationException"></exception>
  261. public string GetImagePath(BaseItem item, ImageType imageType, int imageIndex)
  262. {
  263. if (item == null)
  264. {
  265. throw new ArgumentNullException("item");
  266. }
  267. if (imageType == ImageType.Backdrop)
  268. {
  269. if (item.BackdropImagePaths == null)
  270. {
  271. throw new InvalidOperationException(string.Format("Item {0} does not have any Backdrops.", item.Name));
  272. }
  273. return item.BackdropImagePaths[imageIndex];
  274. }
  275. if (imageType == ImageType.Screenshot)
  276. {
  277. if (item.ScreenshotImagePaths == null)
  278. {
  279. throw new InvalidOperationException(string.Format("Item {0} does not have any Screenshots.", item.Name));
  280. }
  281. return item.ScreenshotImagePaths[imageIndex];
  282. }
  283. if (imageType == ImageType.ChapterImage)
  284. {
  285. var video = (Video)item;
  286. if (video.Chapters == null)
  287. {
  288. throw new InvalidOperationException(string.Format("Item {0} does not have any Chapters.", item.Name));
  289. }
  290. return video.Chapters[imageIndex].ImagePath;
  291. }
  292. return item.GetImage(imageType);
  293. }
  294. /// <summary>
  295. /// Gets the image date modified.
  296. /// </summary>
  297. /// <param name="item">The item.</param>
  298. /// <param name="imageType">Type of the image.</param>
  299. /// <param name="imageIndex">Index of the image.</param>
  300. /// <returns>DateTime.</returns>
  301. /// <exception cref="System.ArgumentNullException">item</exception>
  302. public DateTime GetImageDateModified(BaseItem item, ImageType imageType, int imageIndex)
  303. {
  304. if (item == null)
  305. {
  306. throw new ArgumentNullException("item");
  307. }
  308. var imagePath = GetImagePath(item, imageType, imageIndex);
  309. return GetImageDateModified(item, imagePath);
  310. }
  311. /// <summary>
  312. /// Gets the image date modified.
  313. /// </summary>
  314. /// <param name="item">The item.</param>
  315. /// <param name="imagePath">The image path.</param>
  316. /// <returns>DateTime.</returns>
  317. /// <exception cref="System.ArgumentNullException">item</exception>
  318. public DateTime GetImageDateModified(BaseItem item, string imagePath)
  319. {
  320. if (item == null)
  321. {
  322. throw new ArgumentNullException("item");
  323. }
  324. if (string.IsNullOrEmpty(imagePath))
  325. {
  326. throw new ArgumentNullException("imagePath");
  327. }
  328. var metaFileEntry = item.ResolveArgs.GetMetaFileByPath(imagePath);
  329. // If we didn't the metafile entry, check the Season
  330. if (!metaFileEntry.HasValue)
  331. {
  332. var episode = item as Episode;
  333. if (episode != null && episode.Season != null)
  334. {
  335. episode.Season.ResolveArgs.GetMetaFileByPath(imagePath);
  336. }
  337. }
  338. // See if we can avoid a file system lookup by looking for the file in ResolveArgs
  339. return metaFileEntry == null ? File.GetLastWriteTimeUtc(imagePath) : metaFileEntry.Value.LastWriteTimeUtc;
  340. }
  341. /// <summary>
  342. /// Crops whitespace from an image, caches the result, and returns the cached path
  343. /// </summary>
  344. /// <param name="originalImagePath">The original image path.</param>
  345. /// <param name="dateModified">The date modified.</param>
  346. /// <returns>System.String.</returns>
  347. private string GetCroppedImage(string originalImagePath, DateTime dateModified)
  348. {
  349. var name = originalImagePath;
  350. name += "datemodified=" + dateModified.Ticks;
  351. var croppedImagePath = CroppedImageCache.GetResourcePath(name, Path.GetExtension(originalImagePath));
  352. if (!CroppedImageCache.ContainsFilePath(croppedImagePath))
  353. {
  354. using (var fileStream = File.OpenRead(originalImagePath))
  355. {
  356. using (var originalImage = (Bitmap)Bitmap.FromStream(fileStream, true, false))
  357. {
  358. var outputFormat = originalImage.RawFormat;
  359. using (var croppedImage = originalImage.CropWhitespace())
  360. {
  361. using (var cacheFileStream = new FileStream(croppedImagePath, FileMode.Create))
  362. {
  363. croppedImage.Save(outputFormat, cacheFileStream, 100);
  364. }
  365. }
  366. }
  367. }
  368. }
  369. return croppedImagePath;
  370. }
  371. /// <summary>
  372. /// Runs an image through the image enhancers, caches the result, and returns the cached path
  373. /// </summary>
  374. /// <param name="originalImagePath">The original image path.</param>
  375. /// <param name="dateModified">The date modified of the original image file.</param>
  376. /// <param name="item">The item.</param>
  377. /// <param name="imageType">Type of the image.</param>
  378. /// <param name="imageIndex">Index of the image.</param>
  379. /// <returns>System.String.</returns>
  380. /// <exception cref="System.ArgumentNullException">originalImagePath</exception>
  381. public async Task<string> GetEnhancedImage(string originalImagePath, DateTime dateModified, BaseItem item, ImageType imageType, int imageIndex)
  382. {
  383. if (string.IsNullOrEmpty(originalImagePath))
  384. {
  385. throw new ArgumentNullException("originalImagePath");
  386. }
  387. if (item == null)
  388. {
  389. throw new ArgumentNullException("item");
  390. }
  391. var supportedEnhancers = Kernel.ImageEnhancers.Where(i => i.Supports(item, imageType)).ToList();
  392. // No enhancement - don't cache
  393. if (supportedEnhancers.Count == 0)
  394. {
  395. return originalImagePath;
  396. }
  397. var cacheGuid = GetImageCacheTag(originalImagePath, dateModified, supportedEnhancers, item, imageType);
  398. // All enhanced images are saved as png to allow transparency
  399. var enhancedImagePath = EnhancedImageCache.GetResourcePath(cacheGuid + ".png");
  400. if (!EnhancedImageCache.ContainsFilePath(enhancedImagePath))
  401. {
  402. using (var fileStream = File.OpenRead(originalImagePath))
  403. {
  404. using (var originalImage = Image.FromStream(fileStream, true, false))
  405. {
  406. //Pass the image through registered enhancers
  407. using (var newImage = await ExecuteImageEnhancers(supportedEnhancers, originalImage, item, imageType, imageIndex).ConfigureAwait(false))
  408. {
  409. //And then save it in the cache
  410. newImage.Save(enhancedImagePath, ImageFormat.Png);
  411. }
  412. }
  413. }
  414. }
  415. return enhancedImagePath;
  416. }
  417. /// <summary>
  418. /// Gets the image cache tag.
  419. /// </summary>
  420. /// <param name="item">The item.</param>
  421. /// <param name="imageType">Type of the image.</param>
  422. /// <param name="imagePath">The image path.</param>
  423. /// <returns>Guid.</returns>
  424. /// <exception cref="System.ArgumentNullException">item</exception>
  425. public Guid GetImageCacheTag(BaseItem item, ImageType imageType, string imagePath)
  426. {
  427. if (item == null)
  428. {
  429. throw new ArgumentNullException("item");
  430. }
  431. if (string.IsNullOrEmpty(imagePath))
  432. {
  433. throw new ArgumentNullException("imagePath");
  434. }
  435. var dateModified = GetImageDateModified(item, imagePath);
  436. var supportedEnhancers = Kernel.ImageEnhancers.Where(i => i.Supports(item, imageType));
  437. return GetImageCacheTag(imagePath, dateModified, supportedEnhancers, item, imageType);
  438. }
  439. /// <summary>
  440. /// Gets the image cache tag.
  441. /// </summary>
  442. /// <param name="originalImagePath">The original image path.</param>
  443. /// <param name="dateModified">The date modified of the original image file.</param>
  444. /// <param name="imageEnhancers">The image enhancers.</param>
  445. /// <param name="item">The item.</param>
  446. /// <param name="imageType">Type of the image.</param>
  447. /// <returns>Guid.</returns>
  448. /// <exception cref="System.ArgumentNullException">item</exception>
  449. public Guid GetImageCacheTag(string originalImagePath, DateTime dateModified, IEnumerable<BaseImageEnhancer> imageEnhancers, BaseItem item, ImageType imageType)
  450. {
  451. if (item == null)
  452. {
  453. throw new ArgumentNullException("item");
  454. }
  455. if (imageEnhancers == null)
  456. {
  457. throw new ArgumentNullException("imageEnhancers");
  458. }
  459. if (string.IsNullOrEmpty(originalImagePath))
  460. {
  461. throw new ArgumentNullException("originalImagePath");
  462. }
  463. // Cache name is created with supported enhancers combined with the last config change so we pick up new config changes
  464. var cacheKeys = imageEnhancers.Select(i => i.GetType().Name + i.LastConfigurationChange(item, imageType).Ticks).ToList();
  465. cacheKeys.Add(originalImagePath + dateModified.Ticks);
  466. return string.Join("|", cacheKeys.ToArray()).GetMD5();
  467. }
  468. /// <summary>
  469. /// Executes the image enhancers.
  470. /// </summary>
  471. /// <param name="imageEnhancers">The image enhancers.</param>
  472. /// <param name="originalImage">The original image.</param>
  473. /// <param name="item">The item.</param>
  474. /// <param name="imageType">Type of the image.</param>
  475. /// <param name="imageIndex">Index of the image.</param>
  476. /// <returns>Task{EnhancedImage}.</returns>
  477. private async Task<Image> ExecuteImageEnhancers(IEnumerable<BaseImageEnhancer> imageEnhancers, Image originalImage, BaseItem item, ImageType imageType, int imageIndex)
  478. {
  479. var result = originalImage;
  480. // Run the enhancers sequentially in order of priority
  481. foreach (var enhancer in imageEnhancers)
  482. {
  483. result = await enhancer.EnhanceImageAsync(item, result, imageType, imageIndex).ConfigureAwait(false);
  484. }
  485. return result;
  486. }
  487. /// <summary>
  488. /// Releases unmanaged and - optionally - managed resources.
  489. /// </summary>
  490. /// <param name="dispose"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
  491. protected override void Dispose(bool dispose)
  492. {
  493. if (dispose)
  494. {
  495. ImageSizeCache.Dispose();
  496. ResizedImageCache.Dispose();
  497. CroppedImageCache.Dispose();
  498. EnhancedImageCache.Dispose();
  499. }
  500. base.Dispose(dispose);
  501. }
  502. }
  503. }