SkiaEncoder.cs 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392
  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 = SKBitmapResizeMethod.Lanczos3;
  217. bitmap.Resize(resizedBitmap, resizeMethod);
  218. // If all we're doing is resizing then we can stop now
  219. if (!hasBackgroundColor && !hasForegroundColor && blur == 0 && !hasIndicator)
  220. {
  221. using (var outputStream = new SKFileWStream(outputPath))
  222. {
  223. resizedBitmap.Encode(outputStream, skiaOutputFormat, quality);
  224. return;
  225. }
  226. }
  227. // create bitmap to use for canvas drawing
  228. using (var saveBitmap = new SKBitmap(width, height, bitmap.ColorType, bitmap.AlphaType))
  229. {
  230. // create canvas used to draw into bitmap
  231. using (var canvas = new SKCanvas(saveBitmap))
  232. {
  233. // set background color if present
  234. if (hasBackgroundColor)
  235. {
  236. canvas.Clear(SKColor.Parse(options.BackgroundColor));
  237. }
  238. // Add blur if option is present
  239. if (blur > 0)
  240. {
  241. using (var paint = new SKPaint())
  242. {
  243. // create image from resized bitmap to apply blur
  244. using (var filter = SKImageFilter.CreateBlur(5, 5))
  245. {
  246. paint.ImageFilter = filter;
  247. canvas.DrawBitmap(resizedBitmap, SKRect.Create(width, height), paint);
  248. }
  249. }
  250. }
  251. else
  252. {
  253. // draw resized bitmap onto canvas
  254. canvas.DrawBitmap(resizedBitmap, SKRect.Create(width, height));
  255. }
  256. // If foreground layer present then draw
  257. if (hasForegroundColor)
  258. {
  259. Double opacity;
  260. if (!Double.TryParse(options.ForegroundLayer, out opacity)) opacity = .4;
  261. var foregroundColor = String.Format("#{0:X2}000000", (Byte)((1 - opacity) * 0xFF));
  262. canvas.DrawColor(SKColor.Parse(foregroundColor), SKBlendMode.SrcOver);
  263. }
  264. if (hasIndicator)
  265. {
  266. DrawIndicator(canvas, width, height, options);
  267. }
  268. using (var outputStream = new SKFileWStream(outputPath))
  269. {
  270. saveBitmap.Encode(outputStream, skiaOutputFormat, quality);
  271. }
  272. }
  273. }
  274. }
  275. }
  276. }
  277. public void CreateImageCollage(ImageCollageOptions options)
  278. {
  279. double ratio = options.Width;
  280. ratio /= options.Height;
  281. if (ratio >= 1.4)
  282. {
  283. new StripCollageBuilder(_appPaths, _fileSystem).BuildThumbCollage(options.InputPaths, options.OutputPath, options.Width, options.Height);
  284. }
  285. else if (ratio >= .9)
  286. {
  287. new StripCollageBuilder(_appPaths, _fileSystem).BuildSquareCollage(options.InputPaths, options.OutputPath, options.Width, options.Height);
  288. }
  289. else
  290. {
  291. // @todo create Poster collage capability
  292. new StripCollageBuilder(_appPaths, _fileSystem).BuildSquareCollage(options.InputPaths, options.OutputPath, options.Width, options.Height);
  293. }
  294. }
  295. private void DrawIndicator(SKCanvas canvas, int imageWidth, int imageHeight, ImageProcessingOptions options)
  296. {
  297. try
  298. {
  299. var currentImageSize = new ImageSize(imageWidth, imageHeight);
  300. if (options.AddPlayedIndicator)
  301. {
  302. var task = new PlayedIndicatorDrawer(_appPaths, _httpClientFactory(), _fileSystem).DrawPlayedIndicator(canvas, currentImageSize);
  303. Task.WaitAll(task);
  304. }
  305. else if (options.UnplayedCount.HasValue)
  306. {
  307. new UnplayedCountIndicator(_appPaths, _httpClientFactory(), _fileSystem).DrawUnplayedCountIndicator(canvas, currentImageSize, options.UnplayedCount.Value);
  308. }
  309. if (options.PercentPlayed > 0)
  310. {
  311. new PercentPlayedDrawer().Process(canvas, currentImageSize, options.PercentPlayed);
  312. }
  313. }
  314. catch (Exception ex)
  315. {
  316. _logger.ErrorException("Error drawing indicator overlay", ex);
  317. }
  318. }
  319. public string Name
  320. {
  321. get { return "Skia"; }
  322. }
  323. private bool _disposed;
  324. public void Dispose()
  325. {
  326. _disposed = true;
  327. }
  328. private void CheckDisposed()
  329. {
  330. if (_disposed)
  331. {
  332. throw new ObjectDisposedException(GetType().Name);
  333. }
  334. }
  335. public bool SupportsImageCollageCreation
  336. {
  337. get { return true; }
  338. }
  339. public bool SupportsImageEncoding
  340. {
  341. get { return true; }
  342. }
  343. }
  344. }