python通过PIL缩放互联网上的图片并保存的代码

本文介绍了一段Python代码,该代码利用PIL库从互联网上下载图片,根据指定尺寸进行缩放,保持原始比例,并能显示和保存缩放后的图像。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

下面的代码内容是关于python通过PIL缩放互联网上的图片并保存的代码,应该对小伙伴有较大用。

‘’’ 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
‘’’
factor = min([f1, f2])
#print(f1, f2, factor) # test
# use best down-sizing filter
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

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()

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值