SkiaEncoder.cs 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395
  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 Decode(string path)
  174. {
  175. using (var stream = new SKFileStream(path))
  176. {
  177. var codec = SKCodec.Create(stream);
  178. // create the bitmap
  179. var bitmap = new SKBitmap(codec.Info.Width, codec.Info.Height);
  180. // decode
  181. codec.GetPixels(bitmap.Info, bitmap.GetPixels());
  182. return bitmap;
  183. }
  184. }
  185. private SKBitmap GetBitmap(string path, bool cropWhitespace)
  186. {
  187. if (cropWhitespace)
  188. {
  189. using (var bitmap = Decode(path))
  190. {
  191. return CropWhiteSpace(bitmap);
  192. }
  193. }
  194. return Decode(path);
  195. }
  196. public void EncodeImage(string inputPath, string outputPath, bool autoOrient, int width, int height, int quality, ImageProcessingOptions options, ImageFormat selectedOutputFormat)
  197. {
  198. if (string.IsNullOrWhiteSpace(inputPath))
  199. {
  200. throw new ArgumentNullException("inputPath");
  201. }
  202. if (string.IsNullOrWhiteSpace(inputPath))
  203. {
  204. throw new ArgumentNullException("outputPath");
  205. }
  206. var skiaOutputFormat = GetImageFormat(selectedOutputFormat);
  207. var hasBackgroundColor = !string.IsNullOrWhiteSpace(options.BackgroundColor);
  208. var hasForegroundColor = !string.IsNullOrWhiteSpace(options.ForegroundLayer);
  209. var blur = options.Blur ?? 0;
  210. var hasIndicator = !options.AddPlayedIndicator && !options.UnplayedCount.HasValue && options.PercentPlayed.Equals(0);
  211. using (var bitmap = GetBitmap(inputPath, options.CropWhiteSpace))
  212. {
  213. using (var resizedBitmap = new SKBitmap(width, height, bitmap.ColorType, bitmap.AlphaType))
  214. {
  215. // scale image
  216. var resizeMethod = options.Image.Type == MediaBrowser.Model.Entities.ImageType.Logo ||
  217. options.Image.Type == MediaBrowser.Model.Entities.ImageType.Art
  218. ? SKBitmapResizeMethod.Lanczos3
  219. : SKBitmapResizeMethod.Lanczos3;
  220. bitmap.Resize(resizedBitmap, resizeMethod);
  221. // If all we're doing is resizing then we can stop now
  222. if (!hasBackgroundColor && !hasForegroundColor && blur == 0 && !hasIndicator)
  223. {
  224. using (var outputStream = new SKFileWStream(outputPath))
  225. {
  226. resizedBitmap.Encode(outputStream, skiaOutputFormat, quality);
  227. return;
  228. }
  229. }
  230. // create bitmap to use for canvas drawing
  231. using (var saveBitmap = new SKBitmap(width, height, bitmap.ColorType, bitmap.AlphaType))
  232. {
  233. // create canvas used to draw into bitmap
  234. using (var canvas = new SKCanvas(saveBitmap))
  235. {
  236. // set background color if present
  237. if (hasBackgroundColor)
  238. {
  239. canvas.Clear(SKColor.Parse(options.BackgroundColor));
  240. }
  241. // Add blur if option is present
  242. if (blur > 0)
  243. {
  244. using (var paint = new SKPaint())
  245. {
  246. // create image from resized bitmap to apply blur
  247. using (var filter = SKImageFilter.CreateBlur(5, 5))
  248. {
  249. paint.ImageFilter = filter;
  250. canvas.DrawBitmap(resizedBitmap, SKRect.Create(width, height), paint);
  251. }
  252. }
  253. }
  254. else
  255. {
  256. // draw resized bitmap onto canvas
  257. canvas.DrawBitmap(resizedBitmap, SKRect.Create(width, height));
  258. }
  259. // If foreground layer present then draw
  260. if (hasForegroundColor)
  261. {
  262. Double opacity;
  263. if (!Double.TryParse(options.ForegroundLayer, out opacity)) opacity = .4;
  264. var foregroundColor = String.Format("#{0:X2}000000", (Byte)((1 - opacity) * 0xFF));
  265. canvas.DrawColor(SKColor.Parse(foregroundColor), SKBlendMode.SrcOver);
  266. }
  267. if (hasIndicator)
  268. {
  269. DrawIndicator(canvas, width, height, options);
  270. }
  271. using (var outputStream = new SKFileWStream(outputPath))
  272. {
  273. saveBitmap.Encode(outputStream, skiaOutputFormat, quality);
  274. }
  275. }
  276. }
  277. }
  278. }
  279. }
  280. public void CreateImageCollage(ImageCollageOptions options)
  281. {
  282. double ratio = options.Width;
  283. ratio /= options.Height;
  284. if (ratio >= 1.4)
  285. {
  286. new StripCollageBuilder(_appPaths, _fileSystem).BuildThumbCollage(options.InputPaths, options.OutputPath, options.Width, options.Height);
  287. }
  288. else if (ratio >= .9)
  289. {
  290. new StripCollageBuilder(_appPaths, _fileSystem).BuildSquareCollage(options.InputPaths, options.OutputPath, options.Width, options.Height);
  291. }
  292. else
  293. {
  294. // @todo create Poster collage capability
  295. new StripCollageBuilder(_appPaths, _fileSystem).BuildSquareCollage(options.InputPaths, options.OutputPath, options.Width, options.Height);
  296. }
  297. }
  298. private void DrawIndicator(SKCanvas canvas, int imageWidth, int imageHeight, ImageProcessingOptions options)
  299. {
  300. try
  301. {
  302. var currentImageSize = new ImageSize(imageWidth, imageHeight);
  303. if (options.AddPlayedIndicator)
  304. {
  305. var task = new PlayedIndicatorDrawer(_appPaths, _httpClientFactory(), _fileSystem).DrawPlayedIndicator(canvas, currentImageSize);
  306. Task.WaitAll(task);
  307. }
  308. else if (options.UnplayedCount.HasValue)
  309. {
  310. new UnplayedCountIndicator(_appPaths, _httpClientFactory(), _fileSystem).DrawUnplayedCountIndicator(canvas, currentImageSize, options.UnplayedCount.Value);
  311. }
  312. if (options.PercentPlayed > 0)
  313. {
  314. new PercentPlayedDrawer().Process(canvas, currentImageSize, options.PercentPlayed);
  315. }
  316. }
  317. catch (Exception ex)
  318. {
  319. _logger.ErrorException("Error drawing indicator overlay", ex);
  320. }
  321. }
  322. public string Name
  323. {
  324. get { return "Skia"; }
  325. }
  326. private bool _disposed;
  327. public void Dispose()
  328. {
  329. _disposed = true;
  330. }
  331. private void CheckDisposed()
  332. {
  333. if (_disposed)
  334. {
  335. throw new ObjectDisposedException(GetType().Name);
  336. }
  337. }
  338. public bool SupportsImageCollageCreation
  339. {
  340. get { return true; }
  341. }
  342. public bool SupportsImageEncoding
  343. {
  344. get { return true; }
  345. }
  346. }
  347. }