PixelFormatHelper.cs 2.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. using SkiaSharp;
  2. using System;
  3. using System.Windows.Media;
  4. namespace PixiEditor.Helpers.Extensions
  5. {
  6. public static class PixelFormatHelper
  7. {
  8. public static SKColorType ToSkia(this PixelFormat format, out SKAlphaType alphaType)
  9. {
  10. if (TryToSkia(format, out SKColorType color, out alphaType))
  11. {
  12. return color;
  13. }
  14. else
  15. {
  16. throw new NotImplementedException($"Skia does not support the '{format}' format");
  17. }
  18. }
  19. public static bool TryToSkia(this PixelFormat format, out SKColorType colorType, out SKAlphaType alphaType)
  20. {
  21. if (format == PixelFormats.Rgba64)
  22. {
  23. alphaType = SKAlphaType.Unpremul;
  24. colorType = SKColorType.Rgba16161616;
  25. return true;
  26. }
  27. else if (format == PixelFormats.Bgra32)
  28. {
  29. alphaType = SKAlphaType.Unpremul;
  30. colorType = SKColorType.Bgra8888;
  31. return true;
  32. }
  33. else if (format == PixelFormats.Default)
  34. {
  35. alphaType = SKAlphaType.Unpremul;
  36. colorType = SKColorType.RgbaF16;
  37. return true;
  38. }
  39. else if (format == PixelFormats.Gray8)
  40. {
  41. alphaType = SKAlphaType.Opaque;
  42. colorType = SKColorType.Gray8;
  43. return true;
  44. }
  45. else if (format == PixelFormats.Pbgra32)
  46. {
  47. alphaType = SKAlphaType.Premul;
  48. colorType = SKColorType.Bgra8888;
  49. return true;
  50. }
  51. else if (format == PixelFormats.Bgr101010 || format == PixelFormats.Bgr24 || format == PixelFormats.Bgr32 || format == PixelFormats.Bgr555 ||
  52. format == PixelFormats.Bgr565 || format == PixelFormats.BlackWhite || format == PixelFormats.Cmyk32 || format == PixelFormats.Gray16 ||
  53. format == PixelFormats.Gray2 || format == PixelFormats.Gray32Float || format == PixelFormats.Gray4 || format == PixelFormats.Indexed1 ||
  54. format == PixelFormats.Indexed2 || format == PixelFormats.Indexed4 || format == PixelFormats.Indexed8 || format == PixelFormats.Prgba128Float ||
  55. format == PixelFormats.Prgba64 || format == PixelFormats.Rgb128Float || format == PixelFormats.Rgb24 || format == PixelFormats.Rgb48 ||
  56. format == PixelFormats.Rgba128Float)
  57. {
  58. alphaType = SKAlphaType.Unknown;
  59. colorType = SKColorType.Unknown;
  60. return false;
  61. }
  62. throw new NotImplementedException($"'{format}' has not been implemented by {nameof(PixelFormatHelper)}.{nameof(TryToSkia)}()");
  63. }
  64. public static bool IsSkiaSupported(this PixelFormat format)
  65. {
  66. return TryToSkia(format, out _, out _);
  67. }
  68. }
  69. }