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?
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)
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With