如何找到文件夹下的所有图片并保存在一起 python代码实现
时间: 2023-12-29 21:03:02 浏览: 27
可以使用Python的os和Pillow库来实现。以下是示例代码:
```python
import os
from PIL import Image
# 设置要搜索的文件夹路径和保存图片的文件名
folder_path = '/path/to/folder'
save_file_name = 'all_images.jpg'
# 获取文件夹中所有文件名
file_names = os.listdir(folder_path)
# 用于存储所有图片的列表
images = []
# 遍历所有文件名,如果是图片则打开并添加到列表中
for file_name in file_names:
if file_name.lower().endswith('.jpg') or file_name.lower().endswith('.png') or file_name.lower().endswith('.jpeg'):
file_path = os.path.join(folder_path, file_name)
try:
image = Image.open(file_path)
images.append(image)
except:
pass
# 如果没有找到任何图片则退出程序
if len(images) == 0:
print('No images found in folder.')
exit()
# 计算所有图片的总宽度和高度
total_width = 0
max_height = 0
for image in images:
total_width += image.width
max_height = max(max_height, image.height)
# 创建一个新的图像,大小为所有图片的总宽度和最大高度
new_image = Image.new('RGB', (total_width, max_height))
# 将所有图片粘贴到新图像中
x_offset = 0
for image in images:
new_image.paste(image, (x_offset, 0))
x_offset += image.width
# 保存新图像
new_image.save(save_file_name)
print('All images saved to', save_file_name)
```
使用时,将`folder_path`和`save_file_name`替换为相应的文件夹路径和保存文件名即可。该程序会搜索指定文件夹下的所有.jpg、.png和.jpeg格式的图片,并将它们合并成一张新的图像保存在当前目录下。