GDIImageEncoder.cs 9.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257
  1. using MediaBrowser.Common.IO;
  2. using MediaBrowser.Controller.Drawing;
  3. using MediaBrowser.Model.Drawing;
  4. using MediaBrowser.Model.Logging;
  5. using System;
  6. using System.Drawing;
  7. using System.Drawing.Drawing2D;
  8. using System.Drawing.Imaging;
  9. using System.IO;
  10. using System.Linq;
  11. using CommonIO;
  12. using ImageFormat = MediaBrowser.Model.Drawing.ImageFormat;
  13. namespace Emby.Drawing.GDI
  14. {
  15. public class GDIImageEncoder : IImageEncoder
  16. {
  17. private readonly IFileSystem _fileSystem;
  18. private readonly ILogger _logger;
  19. public GDIImageEncoder(IFileSystem fileSystem, ILogger logger)
  20. {
  21. _fileSystem = fileSystem;
  22. _logger = logger;
  23. _logger.Info("GDI image processor initialized");
  24. }
  25. public string[] SupportedInputFormats
  26. {
  27. get
  28. {
  29. return new[]
  30. {
  31. "png",
  32. "jpeg",
  33. "jpg",
  34. "gif",
  35. "bmp"
  36. };
  37. }
  38. }
  39. public ImageFormat[] SupportedOutputFormats
  40. {
  41. get
  42. {
  43. return new[] { ImageFormat.Gif, ImageFormat.Jpg, ImageFormat.Png };
  44. }
  45. }
  46. public ImageSize GetImageSize(string path)
  47. {
  48. using (var image = Image.FromFile(path))
  49. {
  50. return new ImageSize
  51. {
  52. Width = image.Width,
  53. Height = image.Height
  54. };
  55. }
  56. }
  57. public void CropWhiteSpace(string inputPath, string outputPath)
  58. {
  59. using (var image = (Bitmap)Image.FromFile(inputPath))
  60. {
  61. using (var croppedImage = image.CropWhitespace())
  62. {
  63. _fileSystem.CreateDirectory(Path.GetDirectoryName(outputPath));
  64. using (var outputStream = _fileSystem.GetFileStream(outputPath, FileMode.Create, FileAccess.Write, FileShare.Read, false))
  65. {
  66. croppedImage.Save(System.Drawing.Imaging.ImageFormat.Png, outputStream, 100);
  67. }
  68. }
  69. }
  70. }
  71. public void EncodeImage(string inputPath, string cacheFilePath, int width, int height, int quality, ImageProcessingOptions options)
  72. {
  73. var hasPostProcessing = !string.IsNullOrEmpty(options.BackgroundColor) || options.UnplayedCount.HasValue || options.AddPlayedIndicator || options.PercentPlayed > 0;
  74. using (var originalImage = Image.FromFile(inputPath))
  75. {
  76. var newWidth = Convert.ToInt32(width);
  77. var newHeight = Convert.ToInt32(height);
  78. var selectedOutputFormat = options.OutputFormat;
  79. // Graphics.FromImage will throw an exception if the PixelFormat is Indexed, so we need to handle that here
  80. // Also, Webp only supports Format32bppArgb and Format32bppRgb
  81. var pixelFormat = selectedOutputFormat == ImageFormat.Webp
  82. ? PixelFormat.Format32bppArgb
  83. : PixelFormat.Format32bppPArgb;
  84. using (var thumbnail = new Bitmap(newWidth, newHeight, pixelFormat))
  85. {
  86. // Mono throw an exeception if assign 0 to SetResolution
  87. if (originalImage.HorizontalResolution > 0 && originalImage.VerticalResolution > 0)
  88. {
  89. // Preserve the original resolution
  90. thumbnail.SetResolution(originalImage.HorizontalResolution, originalImage.VerticalResolution);
  91. }
  92. using (var thumbnailGraph = Graphics.FromImage(thumbnail))
  93. {
  94. thumbnailGraph.CompositingQuality = CompositingQuality.HighQuality;
  95. thumbnailGraph.SmoothingMode = SmoothingMode.HighQuality;
  96. thumbnailGraph.InterpolationMode = InterpolationMode.HighQualityBicubic;
  97. thumbnailGraph.PixelOffsetMode = PixelOffsetMode.HighQuality;
  98. thumbnailGraph.CompositingMode = !hasPostProcessing ?
  99. CompositingMode.SourceCopy :
  100. CompositingMode.SourceOver;
  101. SetBackgroundColor(thumbnailGraph, options);
  102. thumbnailGraph.DrawImage(originalImage, 0, 0, newWidth, newHeight);
  103. DrawIndicator(thumbnailGraph, newWidth, newHeight, options);
  104. var outputFormat = GetOutputFormat(originalImage, selectedOutputFormat);
  105. _fileSystem.CreateDirectory(Path.GetDirectoryName(cacheFilePath));
  106. // Save to the cache location
  107. using (var cacheFileStream = _fileSystem.GetFileStream(cacheFilePath, FileMode.Create, FileAccess.Write, FileShare.Read, false))
  108. {
  109. // Save to the memory stream
  110. thumbnail.Save(outputFormat, cacheFileStream, quality);
  111. }
  112. }
  113. }
  114. }
  115. }
  116. /// <summary>
  117. /// Sets the color of the background.
  118. /// </summary>
  119. /// <param name="graphics">The graphics.</param>
  120. /// <param name="options">The options.</param>
  121. private void SetBackgroundColor(Graphics graphics, ImageProcessingOptions options)
  122. {
  123. var color = options.BackgroundColor;
  124. if (!string.IsNullOrEmpty(color))
  125. {
  126. Color drawingColor;
  127. try
  128. {
  129. drawingColor = ColorTranslator.FromHtml(color);
  130. }
  131. catch
  132. {
  133. drawingColor = ColorTranslator.FromHtml("#" + color);
  134. }
  135. graphics.Clear(drawingColor);
  136. }
  137. }
  138. /// <summary>
  139. /// Draws the indicator.
  140. /// </summary>
  141. /// <param name="graphics">The graphics.</param>
  142. /// <param name="imageWidth">Width of the image.</param>
  143. /// <param name="imageHeight">Height of the image.</param>
  144. /// <param name="options">The options.</param>
  145. private void DrawIndicator(Graphics graphics, int imageWidth, int imageHeight, ImageProcessingOptions options)
  146. {
  147. if (!options.AddPlayedIndicator && !options.UnplayedCount.HasValue && options.PercentPlayed.Equals(0))
  148. {
  149. return;
  150. }
  151. try
  152. {
  153. if (options.AddPlayedIndicator)
  154. {
  155. var currentImageSize = new Size(imageWidth, imageHeight);
  156. new PlayedIndicatorDrawer().DrawPlayedIndicator(graphics, currentImageSize);
  157. }
  158. else if (options.UnplayedCount.HasValue)
  159. {
  160. var currentImageSize = new Size(imageWidth, imageHeight);
  161. new UnplayedCountIndicator().DrawUnplayedCountIndicator(graphics, currentImageSize, options.UnplayedCount.Value);
  162. }
  163. if (options.PercentPlayed > 0)
  164. {
  165. var currentImageSize = new Size(imageWidth, imageHeight);
  166. new PercentPlayedDrawer().Process(graphics, currentImageSize, options.PercentPlayed);
  167. }
  168. }
  169. catch (Exception ex)
  170. {
  171. _logger.ErrorException("Error drawing indicator overlay", ex);
  172. }
  173. }
  174. /// <summary>
  175. /// Gets the output format.
  176. /// </summary>
  177. /// <param name="image">The image.</param>
  178. /// <param name="outputFormat">The output format.</param>
  179. /// <returns>ImageFormat.</returns>
  180. private System.Drawing.Imaging.ImageFormat GetOutputFormat(Image image, ImageFormat outputFormat)
  181. {
  182. switch (outputFormat)
  183. {
  184. case ImageFormat.Bmp:
  185. return System.Drawing.Imaging.ImageFormat.Bmp;
  186. case ImageFormat.Gif:
  187. return System.Drawing.Imaging.ImageFormat.Gif;
  188. case ImageFormat.Jpg:
  189. return System.Drawing.Imaging.ImageFormat.Jpeg;
  190. case ImageFormat.Png:
  191. return System.Drawing.Imaging.ImageFormat.Png;
  192. default:
  193. return image.RawFormat;
  194. }
  195. }
  196. public void CreateImageCollage(ImageCollageOptions options)
  197. {
  198. double ratio = options.Width;
  199. ratio /= options.Height;
  200. if (ratio >= 1.4)
  201. {
  202. DynamicImageHelpers.CreateThumbCollage(options.InputPaths.ToList(), _fileSystem, options.OutputPath, options.Width, options.Height);
  203. }
  204. else if (ratio >= .9)
  205. {
  206. DynamicImageHelpers.CreateSquareCollage(options.InputPaths.ToList(), _fileSystem, options.OutputPath, options.Width, options.Height);
  207. }
  208. else
  209. {
  210. DynamicImageHelpers.CreateSquareCollage(options.InputPaths.ToList(), _fileSystem, options.OutputPath, options.Width, options.Width);
  211. }
  212. }
  213. public void Dispose()
  214. {
  215. }
  216. public string Name
  217. {
  218. get { return "GDI"; }
  219. }
  220. }
  221. }