专业级AI改图小程序 - 魔法改图
无需安装,即扫即用。一句话改图、改字、上色...
魔法改图小程序码
专业改图小程序 - 魔法改图
无需安装。一句话改图、改字、上色...
魔法改图小程序码
魔法改图 小程序
一句话改图、改字、上色...
魔法改图小程序码

如何用Python批量修改图片尺寸?

2026-01发布8次浏览

在Python中批量修改图片尺寸,可以使用Pillow库(PIL的派生库)来实现。Pillow是一个强大的图像处理库,它提供了许多用于处理图像的函数,如调整大小、裁剪、旋转等。以下是一个简单的示例,展示如何使用Pillow批量修改图片的尺寸。

首先,确保你已经安装了Pillow库。如果没有安装,可以使用pip进行安装:

pip install pillow

接下来,你可以使用以下代码来批量修改图片的尺寸:

from PIL import Image
import os

def resize_images(directory, output_directory, size):
    """
    批量修改指定目录中所有图片的尺寸。

    :param directory: 包含原始图片的目录路径
    :param output_directory: 保存修改后图片的目录路径
    :param size: 修改后的图片尺寸,格式为(width, height)
    """
    # 确保输出目录存在
    if not os.path.exists(output_directory):
        os.makedirs(output_directory)

    # 遍历指定目录中的所有文件
    for filename in os.listdir(directory):
        file_path = os.path.join(directory, filename)
        # 检查文件是否为图片
        if os.path.isfile(file_path) and filename.lower().endswith(('.png', '.jpg', '.jpeg', '.bmp', '.gif')):
            try:
                # 打开图片
                with Image.open(file_path) as img:
                    # 修改图片尺寸
                    img = img.resize(size, Image.ANTIALIAS)
                    # 构建输出文件路径
                    output_path = os.path.join(output_directory, filename)
                    # 保存修改后的图片
                    img.save(output_path)
                    print(f"Resized {filename} and saved to {output_path}")
            except Exception as e:
                print(f"Error processing {filename}: {e}")

# 使用示例
directory = 'path/to/your/images'
output_directory = 'path/to/save/resized/images'
size = (800, 600)  # 修改后的尺寸为800x600
resize_images(directory, output_directory, size)

在这个示例中,resize_images函数接受三个参数:原始图片目录、输出目录和修改后的图片尺寸。函数首先确保输出目录存在,然后遍历原始目录中的所有文件,检查每个文件是否为支持的图片格式。如果是,则打开图片,调整其尺寸,并保存到输出目录。

你可以根据需要修改directoryoutput_directorysize变量的值,以适应你的具体需求。