GDIImageEncoder.cs 9.8 KB

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