Search code examples
pythonpython-3.xpython-imaging-librarygtk3

python GTK3 Image from PIL jpg format


I'm trying to open image (jpg) from the buffer (get as blob from Oracle database) as Gtk.Image() and add it to a Gtk window, but I get error "Expected Gtk.Widget, but got PIL.JpegImagePlugin.JpegImageFile". I can show the image with show(), I can window.add jpeg file from path on the disc, and then show the window, but when I try to add jpg from buffer I get the error. Here is what I produced:

my_source=Here_I_get_BLOB_img_from_database()
newimage=Gtk.Image()
newimage=my_source.read()
image=io.BytesIO(newimage)
dt=Image.open(image)
newwindow = Gtk.Window(modal=True)

In this point actually I have jpg in buffer and I can do:

dt.show() # to display the image in system imageviewer

Or save dt as jpg, or add to newwindow a result of image.set_from_file("path with jpg extension") but don't know how to do this:

newwindow.add(dt) 

Or anything with similar effect. How to do this in simplest way?


Solution

  • What worked for me was -

    Gtk.Image to load img from buffer has Pixbuf object, which for example can be loaded from stream. So:

    from gi.repository import (...) GdkPixbuf, GLib, Gio
    (...)
    my_source=Here_I_get_BLOB_img_from_database()
    newimage=my_source.read()
    glib=GLib.Bytes.new(newimage)
    stream = Gio.MemoryInputStream.new_from_bytes(glib)
    pixbuf = GdkPixbuf.Pixbuf.new_from_stream(stream, None)
    image=Gtk.Image().new_from_pixbuf(pixbuf)
    my_window = Gtk.Window(modal=True, title="Image")
    my_window.add(image)
    image.show()
    my_window.show()