python
使用
PIL
缩放网络图片并保存的方法
本文实例讲述了
python
使用
PIL
缩放网络图片并保存的方法。
分享给大家供大家参考。
具体实现方法如下:
'''tk_image_view_url_io_resize.py
displayanimagefromaURLusingTkinter,PILanddata_stream
alsoresizethewebimagetofitacertainsizedisplaywidget
retainingitsaspectratio
Pilfacilitatesresizingandallowsfileformatsotherthengif
testedwithPython27andPython33byvegaseat18mar
'''
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=""