Search code examples
python-3.xpython-imaging-librarygtk4

Convert PIL.Image to/from Gtk.Picture/Gtk.Image in gtk4


I do RGBA image manipulation in PIL(low) and would like to display the resulting image in a gtk4 application. For that, I'd need a seamless PIL.Image <--> Gtk.Picture/Gtk.Image converter. I'd like to avoid using temporary files at all cost. I found helpful hints here and here but was wondering if there was anything more convenient in gtk4?


Solution

  • As of GTK 4.4, this seems to work best:

    buffer = GLib.Bytes.new(pil_image.tobytes())
    gdata = GdkPixbuf.Pixbuf.new_from_bytes(buffer, GdkPixbuf.Colorspace.RGB, True, 8, pil_image.width, pil_image.height, len(pil_image.getbands())*pil_image.width)
    gtk_image = Gtk.Image.new_from_pixbuf(gdata)
    

    Once GTK 4.6+ becomes ubiquitous, GdkPixbuf should be replaced with GdkTexture, via Gdk.Texture.new_from_bytes().