Python 语言 用 Pillow 批量调整图片尺寸 将 2000 张照片压缩至 1080p

Python阿木 发布于 23 小时前 1 次阅读


阿木博主一句话概括:使用Pillow库批量调整Python图片尺寸至1080p

阿木博主为你简单介绍:
随着数字图像处理技术的不断发展,图片尺寸调整成为日常工作中常见的需求。在Python中,Pillow库是一个功能强大的图像处理库,可以轻松实现图片的尺寸调整、裁剪、格式转换等功能。本文将详细介绍如何使用Pillow库批量调整图片尺寸至1080p,并分享一些实用的代码技巧。

一、
在当今社会,图片处理已经成为日常生活和工作中不可或缺的一部分。对于大量图片的处理,手动调整尺寸不仅效率低下,而且容易出错。使用Python脚本自动化处理图片尺寸调整成为了一种趋势。本文将介绍如何使用Pillow库实现这一功能。

二、Pillow库简介
Pillow是一个开源的Python图像处理库,它提供了丰富的图像处理功能,包括图片的打开、保存、裁剪、缩放、格式转换等。Pillow库基于PIL(Python Imaging Library)开发,是PIL的一个友好替代品。

三、批量调整图片尺寸至1080p
以下是一个使用Pillow库批量调整图片尺寸至1080p的示例代码:

python
from PIL import Image
import os

图片尺寸调整函数
def resize_image(image_path, output_path, width, height):
with Image.open(image_path) as img:
img = img.resize((width, height), Image.ANTIALIAS)
img.save(output_path)

批量处理图片
def batch_resize_images(directory, output_directory, width, height):
if not os.path.exists(output_directory):
os.makedirs(output_directory)

for filename in os.listdir(directory):
if filename.lower().endswith(('.png', '.jpg', '.jpeg', '.bmp', '.gif')):
input_path = os.path.join(directory, filename)
output_path = os.path.join(output_directory, filename)
resize_image(input_path, output_path, width, height)
print(f"Resized {filename} to {width}x{height}")

主函数
if __name__ == "__main__":
input_directory = 'path/to/input/directory' 输入目录
output_directory = 'path/to/output/directory' 输出目录
width = 1920 目标宽度
height = 1080 目标高度

batch_resize_images(input_directory, output_directory, width, height)

四、代码解析
1. `resize_image` 函数:该函数接收图片路径、输出路径、目标宽度和高度作为参数,使用Pillow库的`resize`方法调整图片尺寸,并保存到指定路径。

2. `batch_resize_images` 函数:该函数遍历指定目录下的所有图片文件,对每个图片文件调用`resize_image`函数进行尺寸调整,并将处理后的图片保存到输出目录。

3. 主函数:设置输入目录、输出目录、目标宽度和高度,并调用`batch_resize_images`函数进行批量处理。

五、注意事项
1. 在运行脚本之前,请确保Pillow库已安装。可以使用以下命令安装Pillow库:

bash
pip install Pillow

2. 根据实际情况修改输入目录、输出目录、目标宽度和高度等参数。

3. 在处理大量图片时,请确保系统有足够的内存和磁盘空间。

六、总结
本文介绍了如何使用Pillow库批量调整Python图片尺寸至1080p。通过编写简单的脚本,可以轻松实现图片尺寸的自动化调整,提高工作效率。在实际应用中,可以根据需求对脚本进行扩展,实现更多功能。