BitmapExtensions.cs 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. using System.Runtime.InteropServices;
  2. using Avalonia;
  3. using Avalonia.Media.Imaging;
  4. using Avalonia.Platform;
  5. namespace PixiEditor.AvaloniaUI.Helpers.Extensions;
  6. public static class BitmapExtensions
  7. {
  8. public static byte[] ExtractPixels(this Bitmap source)
  9. {
  10. return ExtractPixels(source, out _);
  11. }
  12. /// <summary>
  13. /// Extracts pixels from bitmap and returns them as byte array.
  14. /// </summary>
  15. /// <param name="source">Bitmap to extract pixels from.</param>
  16. /// <param name="address">Address of pinned array of pixels.</param>
  17. /// <returns>Byte array of pixels.</returns>
  18. public static byte[] ExtractPixels(this Bitmap source, out IntPtr address)
  19. {
  20. var size = source.PixelSize;
  21. var stride = size.Width * 4;
  22. int bufferSize = stride * size.Height;
  23. byte[] target = new byte[bufferSize];
  24. address = Marshal.UnsafeAddrOfPinnedArrayElement(target, 0);
  25. source.CopyPixels(new PixelRect(0, 0, size.Width, size.Height), address, bufferSize, stride);
  26. return target;
  27. }
  28. public static WriteableBitmap ToWriteableBitmap(this Bitmap source)
  29. {
  30. var size = source.PixelSize;
  31. var stride = size.Width * 4;
  32. int bufferSize = stride * size.Height;
  33. byte[] target = new byte[bufferSize];
  34. var address = Marshal.UnsafeAddrOfPinnedArrayElement(target, 0);
  35. source.CopyPixels(new PixelRect(0, 0, size.Width, size.Height), address, bufferSize, stride);
  36. return new WriteableBitmap(PixelFormats.Bgra8888, AlphaFormat.Premul, address, size, new Vector(96, 96), stride);
  37. }
  38. }