gpt4 book ai didi

python - 如何设置 GtkImage 的大小

转载 作者:太空宇宙 更新时间:2023-11-04 10:34:14 26 4
gpt4 key购买 nike

我正在从网页下载图片,图片太大(通常最大边缘为 600 像素),我想将其缩小以适合 220x220 像素的框。

我的代码可以正常工作——除了最终尺寸。下载图像,然后放入 GtkImage(它来自 Glade 布局)。我正在将它下载到一个临时文件中,因为我似乎无法将数据从网站直接传输到图像中。现在的问题是这张图片在应用程序中显示时太大了。

f = tempfile.NamedTemporaryFile()
try:
res = urllib2.urlopen('http://hikingtours.hk/images/meetingpoint_%s.jpg'% (self.tours[tourid]['id'], ))
f.write(res.read())

# This f.read() call is necassary, without it, the image
# can not be set properly.
f.read()
self.edit_tour_meetingpoint_image.set_from_file(f.name)
self.edit_tour_meetingpoint_image.show()

except:
raise

f.close()

附带说明一下,我很想摆脱那个临时文件结构:)

请注意,我使用的是 GTK3。

最佳答案

将 Gdk.Pixbuf.new_from_file_at_scale() 与 Gtk.Image.set_from_pixbuf() 一起使用:

pixbuf = GdkPixbuf.Pixbuf.new_from_file_at_scale(f.name, width=220, height=220,
preserve_aspect_ratio=False)
self.edit_tour_meetingpoint_image.set_from_pixbuf(pixbuf)

如果你想保留外观,只需将该参数设置为 True 或使用:GdkPixbuf.Pixbuf.new_from_file_at_size(f.name, width=220, height=220)

旁注:您需要在使用文件之前调用 read() 的原因是因为它已被缓冲并且尚未写入磁盘。 read 调用导致缓冲区刷新,更清晰的技术(从可读性的角度来看)是调用 flush() 而不是 read()。

如果您想删除临时文件,请使用 Gio 模块和流式 pixbuf:

from gi.repository import Gtk, GdkPixbuf, Gio

file = Gio.File.new_for_uri('http://www.gnome.org/wp-content/themes/gnome-grass/images/gnome-logo.png')
pixbuf = GdkPixbuf.Pixbuf.new_from_stream_at_scale(file.read(cancellable=None),
width=220, height=220,
preserve_aspect_ratio=False,
cancellable=None)
self.edit_tour_meetingpoint_image.set_from_pixbuf(pixbuf)

您可以进一步使用异步图像流,然后在 pixbuf 准备就绪时将完成的结果注入(inject)应用程序,在文件传输期间保持 UI 中的交互性:

from gi.repository import Gtk, GdkPixbuf, Gio

# standin image until our remote image is loaded, this can also be set in Glade
image = Gtk.Image.new_from_icon_name('image-missing', Gtk.IconSize.DIALOG)

def on_image_loaded(source, async_res, user_data):
pixbuf = GdkPixbuf.Pixbuf.new_from_stream_finish(async_res)
image.set_from_pixbuf(pixbuf)

file = Gio.File.new_for_uri('http://www.gnome.org/wp-content/themes/gnome-grass/images/gnome-logo.png')
GdkPixbuf.Pixbuf.new_from_stream_at_scale_async(file.read(cancellable=None),
220, 220, # width and height
False, # preserve_aspect_ratio
None, # cancellable
on_image_loaded, # callback,
None) # user_data

请注意,由于 user_data arg,我们不能在异步版本中使用 nice 关键字参数。这在 pygobject 3.12 中消失了,如果不使用(或者也用作关键字参数),user_data 实际上可以被关闭。

关于python - 如何设置 GtkImage 的大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24436585/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com