[Python] 纯文本查看 复制代码from PIL import Image
import os
import re
# 设置小图片所在的目录
image_dir = 'D:/52pj/dizhiyun/' # 替换为你的图片目录路径
output_path = 'D:/52pj/dizhiyun/big_image.png' # 设置输出大图的路径
# 获取目录下所有文件名,并按照“列-行”的规则解析它们
image_files = os.listdir(image_dir)
column_row_pairs = [
(int(re.search(r'(\d+)-(\d+)', file_name).group(1)), int(re.search(r'(\d+)-(\d+)', file_name).group(2)))
for file_name in image_files if re.search(r'(\d+)-(\d+)', file_name)
]
# 对列和行进行排序,确保拼接顺序正确
column_row_pairs.sort(key=lambda x: (x[1], x[0])) # 先按行排序,再按列排序
# 加载一张小图片以获取其尺寸
small_image_path = os.path.join(image_dir, f"{column_row_pairs[0][0]}-{column_row_pairs[0][1]}.png")
small_image = Image.open(small_image_path)
small_image_width, small_image_height = small_image.size
# 初始化大图的尺寸和对象
max_column = max(pair[0] for pair in column_row_pairs)
max_row = max(pair[1] for pair in column_row_pairs)
big_image_width = max_column * small_image_width # 假设所有小图片宽度相同
big_image_height = max_row * small_image_height # 假设所有小图片高度相同
big_image = Image.new('RGB', (big_image_width, big_image_height))
# ... 省略之前的代码 ...
# 加载并拼接小图片到大图中
current_y = 0 # 初始化大图上的当前位置(仅需要y坐标,因为x坐标会在循环中重置)
for row in range(0, max_row + 1): # 按行遍历,从1开始到最大行数
current_x = 0 # 重置x坐标,开始新的一行
for column in range(0, max_column + 1): # 按列遍历,从1开始到最大列数
# 构造小图片的文件名
small_image_path = os.path.join(image_dir, f"{column}-{row}.png")
# 检查文件是否存在,以避免因文件名格式错误或文件缺失导致的错误
if os.path.exists(small_image_path):
small_image = Image.open(small_image_path)
big_image.paste(small_image, (current_x, current_y))
current_x += small_image_width # 移动到下一列的位置
else:
# 如果文件不存在,则跳过,可能需要在这里添加错误处理代码
print(f"Warning: File not found: {small_image_path}")
# 如果不是最后一行,则换行并增加y坐标
if row