将PIL图像转换为GTK Pixbuf

14 投票
3 回答
5998 浏览
提问于 2025-04-17 05:03

我想知道有没有其他方法可以把PIL图像转换成GTK的Pixbuf。现在我用的代码看起来效率不高,是我找到的一个方法,然后根据自己的需求进行了修改。以下是我目前的代码:

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 

有没有更简单的方法可以做到这个转换呢?

3 个回答

2

我不能使用gtk 3.14(这个版本有一个叫做 new_from_bytes 的方法)[1],所以我做了像你这样的变通方法来让它工作:

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

参考资料:

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

如果你在使用PyGI和GTK+3,这里有一个替代方案,它也不需要依赖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)
13

如果你使用numpy数组的话,可以更高效地完成这个任务:

import numpy
arr = numpy.array(im)
return gtk.gdk.pixbuf_new_from_array(arr, gtk.gdk.COLORSPACE_RGB, 8)

撰写回答