Python Pillow 简明教程

Python Pillow - Batch Processing Images

使用 Python Pillow 批量处理图像可以让你有效地将相同的编辑或操作同时应用到多张图像上。这种方法对于诸如调整大小、裁剪、重命名、添加水印或格式化图像等任务非常有价值,因为它增强了工作流效率并优化了输出。

当使用大量图像时,这一点特别有用,因为它可以显著提高计算机的速度和效率。它让你对每张图像应用相同的操作,从而节省时间和精力。

Steps for Batch Processing Images

使用 Python Pillow 批量处理图像涉及以下步骤:

  1. 创建图像文件列表: 生成你想要处理的图像的文件路径列表。

  2. 迭代图像列表: 使用循环遍历图像文件列表。你可以使用“for”或“while”循环一次处理每张图像。

  3. 执行图像处理操作: 在循环中,对每张图像应用所需的图像处理操作。这可能包括调整大小、裁剪、应用滤镜、添加文本或水印,或任何其他必要的操作。

  4. 保存已处理的图像: 在对每张图像执行处理操作后,将已处理的图像保存到所需位置。

Resizing Images using Batch Processing

使用 Python Pillow 批量处理调整图像大小是图像处理中的一项常见任务。它涉及将多张图像的尺寸调整到特定大小或宽高比。

Example

这里有一个例子,演示了如何使用 Python Pillow 批量处理一次调整多张图像的大小。在这个例子中,一个指定文件夹中的一系列 JPG 图像被调整到特定大小(例如,700x400)。

from PIL import Image
import glob
import os

# Get a list of image files in the 'Images for Batch Operation' directory
input_directory = "Images for Batch Operation"
output_directory = "Output directory for Batch Operation"

image_files = [f for f in glob.glob(os.path.join(input_directory, "*.jpg"))]

for file in image_files:
   image = Image.open(file)

   # Resize the image to a specific size (e.g., 700x400)
   image = image.resize((700, 400))

   # Save the resized image to the 'Output directory for Batch Operation' directory
   output_path = os.path.join(output_directory, os.path.basename(file))
   image.save(output_path)

以下图像显示了输入目录中可用的图像文件列表:

list of image

如果我们导航到输出图像保存的目录(即,“批量操作的输出目录”),我们将能够看到如下所示的调整大小的图像:

resized images

Renaming Images using the Batch Processing

重命名图像是在批量处理中经常执行的另一项任务。它涉及根据指定模式更改多张图像的文件名。

Example

以下示例给指定 input_directory 中的一批 PNG 图像的名称添加前缀“New_”。它重命名这些图像并将它们保存到 output_directory 中,并使用了新名称。

from PIL import Image
import glob
import os

# Get a list of image files in the 'Images for Batch Operation' directory
input_directory = "Images for Batch Operation"
output_directory = "Output directory for Batch Operation"

image_files = [f for f in glob.glob(os.path.join(input_directory, "*.png"))]

for file in image_files:
   image = Image.open(file)

   # Save the image with the new name to the 'Output directory for Batch Operation' directory
   output_path = os.path.join(output_directory, 'New_'+os.path.basename(file))
   image.save(output_path)

以下图像显示了输入目录中可用的图像文件列表:

image files

如果我们导航到输出图像保存的目录(即,“批量操作的输出目录”),我们将能够看到如下所示的重命名的图像:

output directory