Pixbuf.cs 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. using System;
  2. using System.Collections.Generic;
  3. using System.IO;
  4. using System.Linq;
  5. using System.Runtime.InteropServices;
  6. using System.Text;
  7. using System.Threading.Tasks;
  8. using Avalonia.Platform;
  9. namespace Avalonia.Gtk3.Interop
  10. {
  11. internal class Pixbuf : GObject, IWindowIconImpl
  12. {
  13. Pixbuf(IntPtr handle) : base(handle)
  14. {
  15. }
  16. public static Pixbuf NewFromFile(string filename)
  17. {
  18. using (var ub = new Utf8Buffer(filename))
  19. {
  20. IntPtr err;
  21. var rv = Native.GdkPixbufNewFromFile(ub, out err);
  22. if(rv != IntPtr.Zero)
  23. return new Pixbuf(rv);
  24. throw new GException(err);
  25. }
  26. }
  27. public static unsafe Pixbuf NewFromBytes(byte[] data)
  28. {
  29. fixed (void* bytes = data)
  30. {
  31. using (var stream = Native.GMemoryInputStreamNewFromData(new IntPtr(bytes), new IntPtr(data.Length), IntPtr.Zero))
  32. {
  33. IntPtr err;
  34. var rv = Native.GdkPixbufNewFromStream(stream, IntPtr.Zero, out err);
  35. if (rv != IntPtr.Zero)
  36. return new Pixbuf(rv);
  37. throw new GException(err);
  38. }
  39. }
  40. }
  41. public static Pixbuf NewFromStream(Stream s)
  42. {
  43. if (s is MemoryStream)
  44. return NewFromBytes(((MemoryStream) s).ToArray());
  45. var ms = new MemoryStream();
  46. s.CopyTo(ms);
  47. return NewFromBytes(ms.ToArray());
  48. }
  49. public void Save(Stream outputStream)
  50. {
  51. IntPtr buffer, bufferLen, error;
  52. using (var png = new Utf8Buffer("png"))
  53. if (!Native.GdkPixbufSaveToBufferv(this, out buffer, out bufferLen, png,
  54. IntPtr.Zero, IntPtr.Zero, out error))
  55. throw new GException(error);
  56. var data = new byte[bufferLen.ToInt32()];
  57. Marshal.Copy(buffer, data, 0, bufferLen.ToInt32());
  58. Native.GFree(buffer);
  59. outputStream.Write(data, 0, data.Length);
  60. }
  61. }
  62. }