GDIImageEncoder.cs 9.3 KB

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