GDIImageEncoder.cs 9.9 KB

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