使用urllib和pil调整url图像大小

时间:2015-01-28 15:11:14

标签: python python-2.7 io python-imaging-library urllib

我希望从网址中检索图像,调整其大小(以适当地适应GUI),然后在GUI中显示图像。我相信我有基本的前提......或者至少我知道如何检索和显示图像。我在下面提供了一些示例代码。

import pywapi, pprint, string, urllib, io
from Tkinter import *
from PIL import Image, ImageTk


root = Tk()
root.geometry("1440x900+0+0")
fd = urllib.urlopen("http://images.intellicast.com/WxImages/Radar/den.gif")
imgFile = io.BytesIO(fd.read())
im = ImageTk.PhotoImage(Image.open(imgFile)) # <-- here
image = Label(root, image = im, bd =2)
image.grid(row = 8, column = 0, columnspan = 2, padx = 20, pady = 30)

# This is just some working code for resizing an image from a url
#fd = urllib.urlretrieve("http://images.intellicast.com/WxImages/Radar/den.gif", "den.gif")
#im1 = Image.open("den.gif")    
#im_small = im1.resize((200, 200), Image.ANTIALIAS)
#im_small.save("den.gif")

root.mainloop()

因此两个代码部分都有效,我只是不确定如何恰当地组合它们。谢谢你的时间!

1 个答案:

答案 0 :(得分:3)

im_small传递给PhotoImage而不是Image.open

fd = urllib.urlretrieve("http://images.intellicast.com/WxImages/Radar/den.gif", "den.gif")
im1 = Image.open("den.gif")    
im_small = im1.resize((200, 200), Image.ANTIALIAS)

im = ImageTk.PhotoImage(im_small)
image = Label(root, image = im, bd =2)
image.grid(row = 8, column = 0, columnspan = 2, padx = 20, pady = 30)