python使用PIL缩放网络图片并保存的方法
本文实例讲述了python使用PIL缩放网络图片并保存的方法。分享给大家供大家参考。具体实现方法如下:
'''tk_image_view_url_io_resize.py
displayanimagefromaURLusingTkinter,PILanddata_stream
alsoresizethewebimagetofitacertainsizedisplaywidget
retainingitsaspectratio
Pilfacilitatesresizingandallowsfileformatsotherthengif
testedwithPython27andPython33byvegaseat18mar2013
'''
importio
fromPILimportImage,ImageTk
try:
#Python2
importTkinterastk
fromurllib2importurlopen
exceptImportError:
#Python3
importtkinterastk
fromurllib.requestimporturlopen
defresize(w,h,w_box,h_box,pil_image):
'''
resizeapil_imageobjectsoitwillfitinto
aboxofsizew_boxtimesh_box,butretainaspectratio
'''
f1=1.0*w_box/w#1.0forcesfloatdivisioninPython2
f2=1.0*h_box/h
factor=min([f1,f2])
#print(f1,f2,factor)#test
#usebestdown-sizingfilter
width=int(w*factor)
height=int(h*factor)
returnpil_image.resize((width,height),Image.ANTIALIAS)
root=tk.Tk()
#sizeofimagedisplayboxyouwant
w_box=400
h_box=350
#findyourselfapictureonaninternetwebpageyoulike
#(rightclickonthepicture,underpropertiescopytheaddress)
#alarger(1600x1200)picturefromtheinternet
#urlnameislong,sosplitit
url1="http://freeflowerpictures.net/image/flowers/petunia/"
url2="petunia-flower.jpg"
url=url1+url2
image_bytes=urlopen(url).read()
#internaldatafile
data_stream=io.BytesIO(image_bytes)
#openasaPILimageobject
pil_image=Image.open(data_stream)
#getthesizeoftheimage
w,h=pil_image.size
#resizetheimagesoitretainsitsaspectration
#butfitsintothespecifieddisplaybox
pil_image_resized=resize(w,h,w_box,h_box,pil_image)
#optionallyshowresizedimageinfo...
#getthesizeoftheresizedimage
wr,hr=pil_image_resized.size
#splitoffimagefilename
fname=url.split('/')[-1]
sf="resized{}({}x{})".format(fname,wr,hr)
root.title(sf)
#convertPILimageobjecttoTkinterPhotoImageobject
tk_image=ImageTk.PhotoImage(pil_image_resized)
#puttheimageonawidgetthesizeofthespecifieddisplaybox
label=tk.Label(root,image=tk_image,width=w_box,height=h_box)
label.pack(padx=5,pady=5)
root.mainloop()
希望本文所述对大家的Python程序设计有所帮助。