python使用PIL縮放網(wǎng)絡圖片并保存的方法
更新時間:2015年04月24日 14:53:02 作者:feiwen
這篇文章主要介紹了python使用PIL縮放網(wǎng)絡圖片并保存的方法,涉及Python操作網(wǎng)絡圖片的相關技巧,非常具有實用價值,需要的朋友可以參考下
本文實例講述了python使用PIL縮放網(wǎng)絡圖片并保存的方法。分享給大家供大家參考。具體實現(xiàn)方法如下:
''' tk_image_view_url_io_resize.py display an image from a URL using Tkinter, PIL and data_stream also resize the web image to fit a certain size display widget retaining its aspect ratio Pil facilitates resizing and allows file formats other then gif tested with Python27 and Python33 by vegaseat 18mar2013 ''' import io from PIL import Image, ImageTk try: # Python2 import Tkinter as tk from urllib2 import urlopen except ImportError: # Python3 import tkinter as tk from urllib.request import urlopen def resize(w, h, w_box, h_box, pil_image): ''' resize a pil_image object so it will fit into a box of size w_box times h_box, but retain aspect ratio ''' f1 = 1.0*w_box/w # 1.0 forces float division in Python2 f2 = 1.0*h_box/h factor = min([f1, f2]) #print(f1, f2, factor) # test # use best down-sizing filter width = int(w*factor) height = int(h*factor) return pil_image.resize((width, height), Image.ANTIALIAS) root = tk.Tk() # size of image display box you want w_box = 400 h_box = 350 # find yourself a picture on an internet web page you like # (right click on the picture, under properties copy the address) # a larger (1600 x 1200) picture from the internet # url name is long, so split it url1 = "http://freeflowerpictures.net/image/flowers/petunia/" url2 = "petunia-flower.jpg" url = url1 + url2 image_bytes = urlopen(url).read() # internal data file data_stream = io.BytesIO(image_bytes) # open as a PIL image object pil_image = Image.open(data_stream) # get the size of the image w, h = pil_image.size # resize the image so it retains its aspect ration # but fits into the specified display box pil_image_resized = resize(w, h, w_box, h_box, pil_image) # optionally show resized image info ... # get the size of the resized image wr, hr = pil_image_resized.size # split off image file name fname = url.split('/')[-1] sf = "resized {} ({}x{})".format(fname, wr, hr) root.title(sf) # convert PIL image object to Tkinter PhotoImage object tk_image = ImageTk.PhotoImage(pil_image_resized) # put the image on a widget the size of the specified display box label = tk.Label(root, image=tk_image, width=w_box, height=h_box) label.pack(padx=5, pady=5) root.mainloop()
希望本文所述對大家的Python程序設計有所幫助。
相關文章
關于tensorflow中tf.keras.models.Sequential()的用法
這篇文章主要介紹了關于tensorflow中tf.keras.models.Sequential()的用法,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2024-01-01基于Python實現(xiàn)網(wǎng)頁文章轉(zhuǎn)PDF文檔
有時候看到一篇好的文章,想去保存下來,傳統(tǒng)方式一般是收藏書簽、復制粘貼到文檔或者直接復制鏈接保存,但這也太麻煩了。本文將用Python語言實現(xiàn)將網(wǎng)上的文章轉(zhuǎn)存為PDF文檔,保存電腦上慢慢看2022-05-05了解一下python內(nèi)建模塊collections
這篇文章主要介紹了Python內(nèi)建模塊——collections的相關資料,幫助大家更好的理解和使用python,感興趣的朋友可以了解下2020-09-09Python+Tableau廣東省人口普查可視化的實現(xiàn)
本文將結合實例代碼,介紹Python+Tableau廣東省人口普查可視化,第七次人口普查數(shù)據(jù)分析,繪制歷次人口普查人口數(shù)量變化圖,需要的朋友們下面隨著小編來一起學習學習吧2021-06-06