我能够一次调整每个图像的大小,但是如何以类似方式以一个文件夹以一个文件夹调整所有图像?请帮助我。
from PIL import Image
from resizeimage import resizeimage
with open('test-image.jpeg', 'r+b') as f:
with Image.open(f) as image:
cover = resizeimage.resize_cover(image, [200, 100])
cover.save('test-image-cover.jpeg', image.format)
只是在当前目录中的文件上迭代
import os
from PIL import Image
from resizeimage import resizeimage
base = '/the/path'
for path in os.listdir(base):
with Image.open(os.path.join(base, path)) as image:
cover = resizeimage.resize_cover(image, [200, 100])
cover.save(path, image.format)
更新:现在使用 os.listdir()
而不是 glob.glob()
,因为需要从原来生成新文件名。现在,代码使用其原始文件加上附加后缀将调整大小的图像保存在同一文件夹中。
请注意,Image.open()
想要传递给它的文件路径,而不是打开的文件。
import os
from PIL import Image
from resizeimage import resizeimage
img_folder = '/path/to/img_folder'
fileext = '.jpg'
suffix = '_RESIZED'
for img_filename in os.listdir(img_folder):
filename, ext = os.path.splitext(img_filename)
if ext == fileext:
print(filename, ext)
src_img_filepath = os.path.join(img_folder, img_filename)
dst_img_filepath = os.path.join(img_folder, filename+suffix, ext)
with Image.open(src_img_filepath) as image:
cover = resizeimage.resize_cover(image, [200, 100])
cover.save(dst_img_filepath, image.format)