在GTK中缩放图像

23
在GTK中如何缩放图像?目前我使用PIL来加载图像并事先缩放它们,但是是否有一种方法可以在GTK中完成它?
6个回答

27

使用gtk.gdk.Pixbuf从文件中加载图像:

import gtk
pixbuf = gtk.gdk.pixbuf_new_from_file('/path/to/the/image.png')

然后对其进行缩放:

pixbuf = pixbuf.scale_simple(width, height, gtk.gdk.INTERP_BILINEAR)

如果你想在gtk.Image中使用它,那么创建小部件并从pixbuf设置图像即可。

image = gtk.Image()
image.set_from_pixbuf(pixbuf)

或者可能以直接的方式:

image = gtk.image_new_from_pixbuf(pixbuf)

2
我们能否也用C语言实现这个解决方案...我正在寻找相同的东西,但是使用C和GTK+...使用GtkImage *image = gtk_image_new_from_file()。 - User7723337
有一个打字错误:gkt.Image() - Ikem Krueger

10

在加载前简单地进行缩放可能会更有效。特别是当我使用这些函数从非常大的JPEG图像中加载96x96缩略图时,仍然非常快。

gtk.gdk.pixbuf_new_from_file_at_scale(..)
gtk.gdk.pixbuf_new_from_file_at_size(..)

这种方式使用更少的内存并且更快。将其用 try 和 except 包裹起来,它应该就是可接受的答案了。 - Eric Sebasta

2

从URL中缩放图像。(缩放参考

import pygtk
pygtk.require('2.0')
import gtk
import urllib2

class MainWin:

    def destroy(self, widget, data=None):
        print "destroy signal occurred"
        gtk.main_quit()

    def __init__(self):
        self.window = gtk.Window(gtk.WINDOW_TOPLEVEL)
        self.window.connect("destroy", self.destroy)
        self.window.set_border_width(10)
        self.image=gtk.Image()

        self.response=urllib2.urlopen(
            'http://192.168.1.11/video/1024x768.jpeg')

        self.loader=gtk.gdk.PixbufLoader()         
        self.loader.set_size(200, 100)   
        #### works but throwing: glib.GError: Unrecognized image file format       
        self.loader.write(self.response.read())
        self.loader.close()
        self.image.set_from_pixbuf(self.loader.get_pixbuf())

        self.window.add(self.image)
        self.image.show()


        self.window.show()

    def main(self):
        gtk.main()

if __name__ == "__main__":
    MainWin().main()

*编辑:(解决方法)*

try:
  self.loader=gtk.gdk.PixbufLoader()         
  self.loader.set_size(200, 100)   

            # ignore tihs: 
            #  glib.GError: Unrecognized image file format       

  self.loader.write(self.response.read())
  self.loader.close()
  self.image.set_from_pixbuf(self.loader.get_pixbuf())

except Exception, err:
  print err
  pass

1

有人用C语言实现这个功能。以下是实现方法:

//假设你已经加载了文件并保存了文件名 //GTK_IMAGE(image)是用于显示图像的容器

GdkPixbuf *pb;

pb = gdk_pixbuf_new_from_file(file_name, NULL);
pb = gdk_pixbuf_scale_simple(pb,700,700,GDK_INTERP_BILINEAR);
            gtk_image_set_from_pixbuf(GTK_IMAGE(image), pb);

0

仅供参考,这里有一个解决方案,它根据窗口大小缩放图像(暗示您正在实现这个类扩展GtkWindow)。

let [width, height] = this.get_size(); // Get size of GtkWindow
this._image = new GtkImage();          
let pixbuf = GdkPixbuf.Pixbuf.new_from_file_at_scale(filePath,width,height,true);
this._image.set_from_pixbuf(pixbuf);

-1

实际上,当我们使用gdk_pixbuf_scale_simple(pb,700,700,GDK_INTERP_BILINEAR)函数与定时器事件一起使用时,会导致内存泄漏(如果我们监视任务管理器,内存需求会不断增加,直到杀死进程)。如何解决这个问题?


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接