GDIImageEncoder.cs 9.2 KB

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