PyGTK: creating a pixbuf from image data

John Hunter jdhunter at ace.bsd.uchicago.edu
Thu Mar 18 11:23:03 EST 2004


>>>>> "Edwin" == Edwin Young <edwin at localhost.localdomain> writes:

    Edwin> Right, the problem is getting the data *into* the pixbuf in
    Edwin> the first place. Basically I have the image in a long
    Edwin> string in memory and need to get that into the Pixbuf
    Edwin> somehow. The pixel_array is read-only, so I can't use that.

In matplotlib, I have an image module that renders to a 
unsigned char * buffer in C, and provides an as_str method 
to access that buffer from python.  


char Image_as_str__doc__[] = 
"numrows, numcols, s = as_str()"
"\n"
"Call this function after resize to get the data as string"
;
static PyObject *
Image_as_str(ImageObject *image, PyObject* args) {
  
  if (!PyArg_ParseTuple(args, ":as_str"))
    return NULL;
  
  return Py_BuildValue("lls#", image->rowsOut, image->colsOut, 
		       image->bufferOut, image->colsOut*image->rowsOut*4);
  
  
}

On the pygtk side, I load this into a Pixbuf pixel array as follows
(in this case the image data is RGBA so the array is M x N x 4)

        rows, cols, s = im.as_str()
        X = fromstring(s, UInt8)
        X.shape = cols, rows, 4
        pb=gtk.gdk.Pixbuf(gtk.gdk.COLORSPACE_RGB,
                          has_alpha=1, bits_per_sample=8,
                          width=rows, height=cols)
        try: pa = pb.get_pixels_array()
        except AttributeError: pa = pb.pixel_array

        pa[:,:,:] = X

        gc = self.new_gc()
        pb.render_to_drawable(self.gdkDrawable, gc.gdkGC, 0, 0,
                              int(x), int(self.height-y), rows, cols,
                              gdk.RGB_DITHER_NONE, 0, 0)

This actually works quite well, performance wise.  At least on the
systems I've tested.  You'll need pygtk compiled with numeric support.
In an earlier thread, Cedric just provided a link to a win32 installer
with Numeric if you need it.

JDH 




More information about the Python-list mailing list