Pixbuf.cs 2.1 KB

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