GDIImageEncoder.cs 10 KB

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