How can Python be used to batch process and standardize…

To batch unify image formats and sizes, you can use the PIL library (a fork of the Pillow library) in Python. Here is an example code that you can modify and expand according to your needs:

from PIL import Image
import os

# 设置目标格式和尺寸
target_format = "JPEG"
target_size = (500, 500)

# 遍历指定文件夹中的所有图片文件
input_folder = "/path/to/input/folder"
output_folder = "/path/to/output/folder"
for filename in os.listdir(input_folder):
    if filename.endswith((".jpg", ".jpeg", ".png")):
        # 打开图片文件
        image_path = os.path.join(input_folder, filename)
        image = Image.open(image_path)

        # 统一图片格式
        if image.format != target_format:
            output_path = os.path.join(output_folder, f"{os.path.splitext(filename)[0]}.{target_format.lower()}")
            image.save(output_path, format=target_format)
        else:
            output_path = os.path.join(output_folder, filename)

        # 统一图片尺寸
        if image.size != target_size:
            resized_image = image.resize(target_size)
            resized_image.save(output_path)
        else:
            image.save(output_path)

In the code above, you will need to set input_folder as the directory path containing all the images to be processed, and output_folder as the directory path where the processed images will be saved. The code will then go through all image files in input_folder and open each image.

The code will first check if the image format is the desired one, if not, it will save the image in the desired format. Then, it will check if the image size matches the target size, if not, it will adjust the image to the target size. Finally, the code will save the processed image to the output_folder while keeping the original file name unchanged.

Before running the code, please make sure to install the Pillow library (pip install Pillow) and specify the correct folder path.

bannerAds