Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting PIL Image to GTK Pixbuf

I am looking to see if there is another way to convert a PIL Image to GTK Pixbuf. Right now all I have is what seems to be like inefficient coding practice that I found and hacked to my needs. This is what I have so far:

def image2pixbuf(self,im):  
    file1 = StringIO.StringIO()  
    im.save(file1, "ppm")  
    contents = file1.getvalue()  
    file1.close()  
    loader = gtk.gdk.PixbufLoader("pnm")  
    loader.write(contents, len(contents))  
    pixbuf = loader.get_pixbuf()  
    loader.close()  
    return pixbuf 

Is there some easier way to do this conversion that I missed?

like image 700
bsktball11ch Avatar asked Oct 26 '11 17:10

bsktball11ch


2 Answers

You can do it efficiently if you go via a numpy array:

import numpy
arr = numpy.array(im)
return gtk.gdk.pixbuf_new_from_array(arr, gtk.gdk.COLORSPACE_RGB, 8)
like image 120
maxy Avatar answered Oct 12 '22 04:10

maxy


If you're using PyGI and GTK+3, here's an alternative which also removes the need for a dependency on numpy:

import array
from gi.repository import GdkPixbuf

def image2pixbuf(self,im):
    arr = array.array('B', im.tostring())
    width, height = im.size
    return GdkPixbuf.Pixbuf.new_from_data(arr, GdkPixbuf.Colorspace.RGB,
                                          True, 8, width, height, width * 4)
like image 41
David Planella Avatar answered Oct 12 '22 04:10

David Planella