ImageManager.cs 24 KB

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