在Python中,我们可以使用多种库来处理图片,例如Pillow(PIL的一个分支)。以下是一个简单的脚本,它将遍历指定目录及其所有子目录中的图片文件,并将它们合并为一个单一的图片。
首先,确保你已经安装了Pillow库。如果没有安装,可以通过以下命令安装:
pip install Pillow
以下是合并子文件夹内所有图片的Python脚本:
import os
from PIL import Image
def find_images(directory):
"""在给定目录及其所有子目录中找到所有图片文件。"""
image_extensions = ('.png', '.jpg', '.jpeg', '.bmp', '.gif')
images = []
for root, dirs, files in os.walk(directory):
for file in files:
if file.lower().endswith(image_extensions):
images.append(os.path.join(root, file))
return images
def merge_images(images, output_file):
"""将找到的图片合并为一个单一的图片。"""
images = [Image.open(image) for image in images]
images.sort(key=lambda x: os.path.basename(x.filename))
# 确定输出图片的大小
max_width = max(image.width for image in images)
max_height = sum(image.height for image in images)
# 创建一个空白图片,用于存放所有合并的图片
merged_image = Image.new('RGB', (max_width, max_height))
# 将每个图片添加到空白图片中
current_y = 0
for image in images:
merged_image.paste(image, (0, current_y))
current_y += image.height
# 保存合并后的图片
merged_image.save(output_file)
# 使用示例
if __name__ == "__main__":
directory = 'path/to/your/directory' # 替换为你的目录路径
output_file = 'merged_image.jpg' # 输出文件名
images = find_images(directory)
if images:
merge_images(images, output_file)
print(f"所有图片已合并到 {output_file}")
else:
print("没有找到任何图片文件。")
脚本说明:
find_images(directory) 函数:遍历指定目录及其所有子目录,查找所有支持的图片文件,并返回它们的路径列表。
merge_images(images, output_file) 函数:接收图片路径列表和输出文件名,将所有图片合并为一个单一的图片,并保存到指定的输出文件。
使用示例:脚本末尾提供了一个简单的使用示例,你需要将
directory变量的值替换为你想要合并图片的目录路径,output_file变量的值替换为你希望保存合并后图片的文件名。
运行脚本后,所有找到的图片将被合并为一个单一的图片,并保存到指定的输出文件中。
