[Python] Use the PIL library to modify the size of all image files in the directory in batches

Problem Description:

There is a folder with several pictures and directories in it, and several directories and pictures in its subdirectories... Now it is necessary to adjust the size of all the pictures in the root directory (including the pictures in its subdirectories).

The contents of the root folder are as follows:

b7dfd2e1ecfd4c6eab329b1a0fa097e4.png

 The contents of the subdirectories are as follows:

f069e705dda647c9820c369d15c13773.png

 The current picture size is: 400*700

3acae59c276d413b9093207e5b584040.png

 Code:

import os
from PIL import Image

# 图片所在的路径(根目录)
img_path = r"D:\素材"
# 获取该文件夹下所有的图片
for root, dirs, file_list in os.walk(img_path):
    for file_name in file_list:
        # 获取所有图片文件的路径
        all_file_path = os.path.join(root, file_name)
        file = Image.open(all_file_path)
        # 以高质量修改图片尺寸为(500,700)
        out = file.resize((500, 700), Image.ANTIALIAS)
        # 以同名保存到原路径
        out.save(all_file_path)

Realize the effect:

25e7ac123c8b4cbfa733db0dc5c4cfd8.png

Guess you like

Origin blog.csdn.net/zhou_ge1/article/details/127528716