GDIImageEncoder.cs 9.7 KB

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