Converting PIL Image to GTK Pixbuf

2020-08-17 17:38发布

问题:

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?

回答1:

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)


回答2:

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)


回答3:

I'm not able to use gtk 3.14 (this version has the method new_from_bytes) [1], so did this workaroud like yours in order to get it working:

from gi.repository import GdkPixbuf
import cv2

def image2pixbuf(im): 
  # convert image from BRG to RGB (pnm uses RGB)
  im2 = cv2.cvtColor(im, cv2.COLOR_BGR2RGB)
  # get image dimensions (depth is not used)
  height, width, depth = im2.shape
  pixl = GdkPixbuf.PixbufLoader.new_with_type('pnm')
  # P6 is the magic number of PNM format, 
  # and 255 is the max color allowed, see [2]
  pixl.write("P6 %d %d 255 " % (width, height) + im2.tostring())
  pix = pixl.get_pixbuf()
  pixl.close()
  return pix

References:

  1. https://bugzilla.gnome.org/show_bug.cgi?id=732297
  2. http://en.wikipedia.org/wiki/Netpbm_format