15-第3步_调整图像的大小
第3步:调整图像的大小
只在有宽度或高度超过 SQUARE_FIT_SIZE
时(在这个例子中,是300像素),该程序才应该调整图像的大小,因此将所有调整大小的代码放在一个检查 width
和 height
变量的 if
语句内。在程序中添加以下代码:
#! python3
# resizeAndAddLogo.py - Resizes all images in current working directory to fit
# in a 300x300 square, and adds catlogo.png to the lower-right corner.
import os
from PIL import Image
--snip--
# Check if image needs to be resized.
if width > SQUARE_FIT_SIZE and height > SQUARE_FIT_SIZE:
# Calculate the new width and height to resize to.
if width > height:
❶ height = int((SQUARE_FIT_SIZE / width) * height)
width = SQUARE_FIT_SIZE
else:
❷ width = int((SQUARE_FIT_SIZE / height) * width)
height = SQUARE_FIT_SIZE
# Resize the image.
print('Resizing %s...' % (filename))
❸ im = im.resize((width, height))
--snip--
如果确实需要调整图像大小,就需要弄清楚它是太宽还是太高。如果 width
大于 height
,则高度应该根据宽度同比例减小❶。这个比例是当前宽度除以 SQUARE_FIT_SIZE
的值。新的高度值是这个比例乘以当前高度值。由于除法运算符返回一个浮点值,而 resize()
要求的尺寸是整数,因此要记得将结果用 int()
函数转换成整数。最后,新的 width
值就设置为 SQUARE_FIT_SIZE
。
如果 height
大于或等于 width
(这两种情况都在 else
子句中处理),那么进行同样的计算,只是交换 height
和 width
变量的位置❷。
在 width
和 height
包含新图像尺寸后,将它们传入 resize()
方法,并将返回的 Image
对象保存在 im
中❸。