使用 PIL 调整文件夹中所有图像的大小 [英] resizing all images in a folder using PIL

查看:60
本文介绍了使用 PIL 调整文件夹中所有图像的大小的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我可以一次调整一张图片的大小,但是如何以类似的方式调整一个文件夹中所有图片的大小?请帮帮我.

i'm able to resize each image one at a time,but how can I resize all images in one folder in a similar way? Please help me.

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)

推荐答案

更新: 现在使用 os.listdir() 而不是 glob.glob() 因为需要从原来的文件中生成新的文件名.代码现在将调整大小的图像与其原始文件和添加的后缀保存在同一文件夹中.

Updated: Now uses os.listdir() instead of glob.glob() because of the need generate new file names from the original. Code now saves the resized images in same folder with its original file plus an added suffix.

请注意,Image.open() 需要传递给它的文件路径,而不是打开的文件.

Note that Image.open() wants a file path passed to it, not an opened file.

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)

这篇关于使用 PIL 调整文件夹中所有图像的大小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆