ImageUtils.cs 1.1 KB

1234567891011121314151617181920212223242526272829303132333435363738
  1. using Avalonia.Media;
  2. using Avalonia.Media.Imaging;
  3. using SkiaSharp;
  4. using System;
  5. using System.Collections.Generic;
  6. using System.Linq;
  7. using System.Text;
  8. using System.Threading.Tasks;
  9. namespace InABox.Avalonia;
  10. public static class ImageUtils
  11. {
  12. public static Bitmap? ImageFromBytes(byte[]? value, bool transparent = true)
  13. {
  14. Bitmap? result = null;
  15. if (value?.Any() == true)
  16. {
  17. if (transparent)
  18. {
  19. var skb = SKBitmap.Decode(value);
  20. var transparentColor = skb.GetPixel(0, 0);
  21. var newPixels = skb.Pixels.Select(x => Equals(x, transparentColor) ? SKColors.Transparent : x);
  22. skb.Pixels = newPixels.ToArray();
  23. SKImage image = SKImage.FromPixels(skb.PeekPixels());
  24. SKData encoded = image.Encode(SKEncodedImageFormat.Png, 100);
  25. value = encoded.ToArray();
  26. }
  27. using (var stream = new MemoryStream(value))
  28. {
  29. result = new Bitmap(stream);
  30. }
  31. }
  32. return result;
  33. }
  34. }