14-第2步_遍历所有文件并打开图像
第2步:遍历所有文件并打开图像
现在,需要找到当前工作目录中的每个.png文件和.jpg文件。请注意,你不希望将徽标图像添加到徽标图像本身,所以程序应该跳过所有名为 LOGO_FILENAME
的图像文件。在程序中添加以下代码:
#! 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--
os.makedirs('withLogo', exist_ok=True)
# Loop over all files in the working directory.
❶ for filename in os.listdir('.'):
❷ if not (filename.endswith('.png') or filename.endswith('.jpg')) \
or filename == LOGO_FILENAME:
❸ continue # skip non-image files and the logo file itself
❹ im = Image.open(filename)
width, height = im.size
--snip--
首先, os.makedirs()
调用创建了一个文件夹 withLogo
,用于保存完成的带有徽标的图像,而不是覆盖原始图像文件。关键字参数 exist_ok=True
将防止 os.makedirs()
在withLogo已存在时抛出异常。在用 os.listdir('.')
遍历工作目录中的所有文件时❶,较长的 if
语句❷检查每个 filename
是否以.png或.jpg结束。如果不是,或者该文件是徽标图像本身,循环就跳过它,使用 continue
❸去处理下一个文件。如果 filename
确实以 '.png'
或 '.jpg'
结束(而且不是徽标文件),就将它打开为一个 Image
对象❹,并设置 width
和 height
。