I have some RGBA data in Python 3, and I want to display the image that it represents in the GTK3 window, without using any additional libraries.
The first thing I tried was to edit the Pixbuf data, as in the example (http://developer.gnome.org/gdk-pixbuf/stable/gdk-pixbuf-The-GdkPixbuf-Structure.html#put-pixel - sorry, I am only allowed 2 links) in the documentation (C) using Pixbuf.get_pixels() . This gives me an immutable bytes object, although it obviously won't work. (The gdk-pixbuf bug report (668084, would refer to it if SO let me) covered the same function, but the stuff must have changed a little since then.)
Next, I tried to create a Pixbuf from the data using Pixbuf.new_from_data() , but this is also buggy (see gdk-pixbuf bug 674691) (yes, I comment 3).
Then I looked at Cairo: ImageSurface.create_for_data should do this, but for some reason this is not yet available in Python 3 binding. (I tried this with Python 2, after that turning the surface into Pixbuf and then wrapping it in gtk.Image and it works. But I use Python3 (and even then, this is messy. Cairo is a vector graphics library, after all)).
I found a link somewhere to use PIL to write an image to a PNG file and then read it in Pixbuf, but it's awful, it uses an extra library, and PIL is not yet available for Python 3.
So ... any other methods?
Working code
Based on Havok's answer, here is a working example:
from array import array from gi.repository import Gtk as gtk, GdkPixbuf pixels = array('H') for i in range(20): for j in range(20): px = (i < 10, j >= 10, (i < 10) ^ (j < 10)) pixels.extend(65535 * c for c in px) header = b'P6 20 20 65535 ' img_data = header + pixels w = gtk.Window() w.connect('delete-event', gtk.main_quit) l = GdkPixbuf.PixbufLoader.new_with_type('pnm') l.write(img_data) w.add(gtk.Image.new_from_pixbuf(l.get_pixbuf())) l.close() w.show_all() gtk.main()
Edit: in fact, for the pixels.byteswap() correctness, I think that to add to the header you will need pixels.byteswap() for small systems (although, of course, it does not matter with these colors).