SkiaEncoder.cs 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380
  1. using MediaBrowser.Common.Configuration;
  2. using MediaBrowser.Common.Net;
  3. using MediaBrowser.Controller.Drawing;
  4. using MediaBrowser.Model.Drawing;
  5. using MediaBrowser.Model.IO;
  6. using MediaBrowser.Model.Logging;
  7. using SkiaSharp;
  8. using System;
  9. using System.Reflection;
  10. using System.Threading.Tasks;
  11. namespace Emby.Drawing.Skia
  12. {
  13. public class SkiaEncoder : IImageEncoder
  14. {
  15. private readonly ILogger _logger;
  16. private readonly IApplicationPaths _appPaths;
  17. private readonly Func<IHttpClient> _httpClientFactory;
  18. private readonly IFileSystem _fileSystem;
  19. public SkiaEncoder(ILogger logger, IApplicationPaths appPaths, Func<IHttpClient> httpClientFactory, IFileSystem fileSystem)
  20. {
  21. _logger = logger;
  22. _appPaths = appPaths;
  23. _httpClientFactory = httpClientFactory;
  24. _fileSystem = fileSystem;
  25. LogVersion();
  26. }
  27. public string[] SupportedInputFormats
  28. {
  29. get
  30. {
  31. // Some common file name extensions for RAW picture files include: .cr2, .crw, .dng, .nef, .orf, .rw2, .pef, .arw, .sr2, .srf, and .tif.
  32. return new[]
  33. {
  34. "jpeg",
  35. "jpg",
  36. "png",
  37. "dng",
  38. "webp",
  39. "gif",
  40. "bmp",
  41. "ico",
  42. "astc",
  43. "ktx",
  44. "pkm",
  45. "wbmp"
  46. };
  47. }
  48. }
  49. public ImageFormat[] SupportedOutputFormats
  50. {
  51. get
  52. {
  53. return new[] { ImageFormat.Webp, ImageFormat.Gif, ImageFormat.Jpg, ImageFormat.Png, ImageFormat.Bmp };
  54. }
  55. }
  56. private void LogVersion()
  57. {
  58. _logger.Info("SkiaSharp version: " + GetVersion());
  59. }
  60. public static string GetVersion()
  61. {
  62. using (var bitmap = new SKBitmap())
  63. {
  64. return typeof(SKBitmap).GetTypeInfo().Assembly.GetName().Version.ToString();
  65. }
  66. }
  67. private static bool IsWhiteSpace(SKColor color)
  68. {
  69. return (color.Red == 255 && color.Green == 255 && color.Blue == 255) || color.Alpha == 0;
  70. }
  71. public static SKEncodedImageFormat GetImageFormat(ImageFormat selectedFormat)
  72. {
  73. switch (selectedFormat)
  74. {
  75. case ImageFormat.Bmp:
  76. return SKEncodedImageFormat.Bmp;
  77. case ImageFormat.Jpg:
  78. return SKEncodedImageFormat.Jpeg;
  79. case ImageFormat.Gif:
  80. return SKEncodedImageFormat.Gif;
  81. case ImageFormat.Webp:
  82. return SKEncodedImageFormat.Webp;
  83. default:
  84. return SKEncodedImageFormat.Png;
  85. }
  86. }
  87. private static bool IsAllWhiteRow(SKBitmap bmp, int row)
  88. {
  89. for (var i = 0; i < bmp.Width; ++i)
  90. {
  91. if (!IsWhiteSpace(bmp.GetPixel(i, row)))
  92. {
  93. return false;
  94. }
  95. }
  96. return true;
  97. }
  98. private static bool IsAllWhiteColumn(SKBitmap bmp, int col)
  99. {
  100. for (var i = 0; i < bmp.Height; ++i)
  101. {
  102. if (!IsWhiteSpace(bmp.GetPixel(col, i)))
  103. {
  104. return false;
  105. }
  106. }
  107. return true;
  108. }
  109. private SKBitmap CropWhiteSpace(SKBitmap bitmap)
  110. {
  111. CheckDisposed();
  112. var topmost = 0;
  113. for (int row = 0; row < bitmap.Height; ++row)
  114. {
  115. if (IsAllWhiteRow(bitmap, row))
  116. topmost = row;
  117. else break;
  118. }
  119. int bottommost = 0;
  120. for (int row = bitmap.Height - 1; row >= 0; --row)
  121. {
  122. if (IsAllWhiteRow(bitmap, row))
  123. bottommost = row;
  124. else break;
  125. }
  126. int leftmost = 0, rightmost = 0;
  127. for (int col = 0; col < bitmap.Width; ++col)
  128. {
  129. if (IsAllWhiteColumn(bitmap, col))
  130. leftmost = col;
  131. else
  132. break;
  133. }
  134. for (int col = bitmap.Width - 1; col >= 0; --col)
  135. {
  136. if (IsAllWhiteColumn(bitmap, col))
  137. rightmost = col;
  138. else
  139. break;
  140. }
  141. var newRect = SKRectI.Create(leftmost, topmost, rightmost - leftmost, bottommost - topmost);
  142. using (var image = SKImage.FromBitmap(bitmap))
  143. {
  144. using (var subset = image.Subset(newRect))
  145. {
  146. return SKBitmap.FromImage(subset);
  147. //using (var data = subset.Encode(StripCollageBuilder.GetEncodedFormat(outputPath), 90))
  148. //{
  149. // using (var fileStream = _fileSystem.GetFileStream(outputPath, FileOpenMode.Create, FileAccessMode.Write, FileShareMode.Read))
  150. // {
  151. // data.AsStream().CopyTo(fileStream);
  152. // }
  153. //}
  154. }
  155. }
  156. }
  157. public ImageSize GetImageSize(string path)
  158. {
  159. CheckDisposed();
  160. using (var s = new SKFileStream(path))
  161. {
  162. using (var codec = SKCodec.Create(s))
  163. {
  164. var info = codec.Info;
  165. return new ImageSize
  166. {
  167. Width = info.Width,
  168. Height = info.Height
  169. };
  170. }
  171. }
  172. }
  173. private SKBitmap GetBitmap(string path, bool cropWhitespace)
  174. {
  175. if (cropWhitespace)
  176. {
  177. using (var bitmap = SKBitmap.Decode(path))
  178. {
  179. return CropWhiteSpace(bitmap);
  180. }
  181. }
  182. return SKBitmap.Decode(path);
  183. }
  184. public void EncodeImage(string inputPath, string outputPath, bool autoOrient, int width, int height, int quality, ImageProcessingOptions options, ImageFormat selectedOutputFormat)
  185. {
  186. if (string.IsNullOrWhiteSpace(inputPath))
  187. {
  188. throw new ArgumentNullException("inputPath");
  189. }
  190. if (string.IsNullOrWhiteSpace(inputPath))
  191. {
  192. throw new ArgumentNullException("outputPath");
  193. }
  194. var skiaOutputFormat = GetImageFormat(selectedOutputFormat);
  195. var hasBackgroundColor = !string.IsNullOrWhiteSpace(options.BackgroundColor);
  196. var hasForegroundColor = !string.IsNullOrWhiteSpace(options.ForegroundLayer);
  197. var blur = options.Blur ?? 0;
  198. var hasIndicator = !options.AddPlayedIndicator && !options.UnplayedCount.HasValue && options.PercentPlayed.Equals(0);
  199. using (var bitmap = GetBitmap(inputPath, options.CropWhiteSpace))
  200. {
  201. using (var resizedBitmap = new SKBitmap(width, height, bitmap.ColorType, bitmap.AlphaType))
  202. {
  203. // scale image
  204. var resizeMethod = options.Image.Type == MediaBrowser.Model.Entities.ImageType.Logo ||
  205. options.Image.Type == MediaBrowser.Model.Entities.ImageType.Art
  206. ? SKBitmapResizeMethod.Lanczos3
  207. : SKBitmapResizeMethod.Lanczos3;
  208. bitmap.Resize(resizedBitmap, resizeMethod);
  209. // If all we're doing is resizing then we can stop now
  210. if (!hasBackgroundColor && !hasForegroundColor && blur == 0 && !hasIndicator)
  211. {
  212. using (var outputStream = new SKFileWStream(outputPath))
  213. {
  214. resizedBitmap.Encode(outputStream, skiaOutputFormat, quality);
  215. return;
  216. }
  217. }
  218. // create bitmap to use for canvas drawing
  219. using (var saveBitmap = new SKBitmap(width, height, bitmap.ColorType, bitmap.AlphaType))
  220. {
  221. // create canvas used to draw into bitmap
  222. using (var canvas = new SKCanvas(saveBitmap))
  223. {
  224. // set background color if present
  225. if (hasBackgroundColor)
  226. {
  227. canvas.Clear(SKColor.Parse(options.BackgroundColor));
  228. }
  229. // Add blur if option is present
  230. if (blur > 0)
  231. {
  232. using (var paint = new SKPaint())
  233. {
  234. // create image from resized bitmap to apply blur
  235. using (var filter = SKImageFilter.CreateBlur(5, 5))
  236. {
  237. paint.ImageFilter = filter;
  238. canvas.DrawBitmap(resizedBitmap, SKRect.Create(width, height), paint);
  239. }
  240. }
  241. }
  242. else
  243. {
  244. // draw resized bitmap onto canvas
  245. canvas.DrawBitmap(resizedBitmap, SKRect.Create(width, height));
  246. }
  247. // If foreground layer present then draw
  248. if (hasForegroundColor)
  249. {
  250. Double opacity;
  251. if (!Double.TryParse(options.ForegroundLayer, out opacity)) opacity = .4;
  252. var foregroundColor = String.Format("#{0:X2}000000", (Byte)((1 - opacity) * 0xFF));
  253. canvas.DrawColor(SKColor.Parse(foregroundColor), SKBlendMode.SrcOver);
  254. }
  255. if (hasIndicator)
  256. {
  257. DrawIndicator(canvas, width, height, options);
  258. }
  259. using (var outputStream = new SKFileWStream(outputPath))
  260. {
  261. saveBitmap.Encode(outputStream, skiaOutputFormat, quality);
  262. }
  263. }
  264. }
  265. }
  266. }
  267. }
  268. public void CreateImageCollage(ImageCollageOptions options)
  269. {
  270. double ratio = options.Width;
  271. ratio /= options.Height;
  272. if (ratio >= 1.4)
  273. {
  274. new StripCollageBuilder(_appPaths, _fileSystem).BuildThumbCollage(options.InputPaths, options.OutputPath, options.Width, options.Height);
  275. }
  276. else if (ratio >= .9)
  277. {
  278. new StripCollageBuilder(_appPaths, _fileSystem).BuildSquareCollage(options.InputPaths, options.OutputPath, options.Width, options.Height);
  279. }
  280. else
  281. {
  282. // @todo create Poster collage capability
  283. new StripCollageBuilder(_appPaths, _fileSystem).BuildSquareCollage(options.InputPaths, options.OutputPath, options.Width, options.Height);
  284. }
  285. }
  286. private void DrawIndicator(SKCanvas canvas, int imageWidth, int imageHeight, ImageProcessingOptions options)
  287. {
  288. try
  289. {
  290. var currentImageSize = new ImageSize(imageWidth, imageHeight);
  291. if (options.AddPlayedIndicator)
  292. {
  293. var task = new PlayedIndicatorDrawer(_appPaths, _httpClientFactory(), _fileSystem).DrawPlayedIndicator(canvas, currentImageSize);
  294. Task.WaitAll(task);
  295. }
  296. else if (options.UnplayedCount.HasValue)
  297. {
  298. new UnplayedCountIndicator(_appPaths, _httpClientFactory(), _fileSystem).DrawUnplayedCountIndicator(canvas, currentImageSize, options.UnplayedCount.Value);
  299. }
  300. if (options.PercentPlayed > 0)
  301. {
  302. new PercentPlayedDrawer().Process(canvas, currentImageSize, options.PercentPlayed);
  303. }
  304. }
  305. catch (Exception ex)
  306. {
  307. _logger.ErrorException("Error drawing indicator overlay", ex);
  308. }
  309. }
  310. public string Name
  311. {
  312. get { return "Skia"; }
  313. }
  314. private bool _disposed;
  315. public void Dispose()
  316. {
  317. _disposed = true;
  318. }
  319. private void CheckDisposed()
  320. {
  321. if (_disposed)
  322. {
  323. throw new ObjectDisposedException(GetType().Name);
  324. }
  325. }
  326. public bool SupportsImageCollageCreation
  327. {
  328. get { return true; }
  329. }
  330. public bool SupportsImageEncoding
  331. {
  332. get { return true; }
  333. }
  334. }
  335. }