Python怎么实现批量统一图片格式和尺寸

462
2024/1/17 14:12:58
栏目: 编程语言
开发者测试专用服务器限时活动,0元免费领,库存有限,领完即止! 点击查看>>

要批量统一图片格式和尺寸,你可以使用Python的PIL库(Pillow库的fork)来实现。以下是一个示例代码,你可以根据自己的需求进行修改和扩展:

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)

在上述代码中,你需要设置input_folder为包含所有要处理图片的文件夹路径,output_folder为处理后图片保存的文件夹路径。然后,代码会遍历input_folder中的所有图片文件,并打开每张图片。

代码首先会检查图片的格式是否为目标格式,如果不是,则将图片保存为目标格式。然后,代码会检查图片的尺寸是否与目标尺寸相同,如果不同,则将图片调整为目标尺寸。最后,代码将保存处理后的图片到output_folder中,保持原始文件名不变。

请注意,在运行代码之前,你需要安装Pillow库(pip install Pillow)和指定正确的文件夹路径。

辰迅云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>

推荐阅读: python的socket库怎么使用