pillow处理图片横向与纵向的合并
一、代码
from PIL import Image path_up = None # 记录合并后的图片地址 save_path1 = r".\拼图上.png" save_path2 = r".\拼图下.png" save_path3 = r".\完整拼图.png" def image_join(png1, png2, save_path, flag='lateral'): """ :param png1: path :param png2: path :param flag: lateral or vertical :return: """ img1, img2 = Image.open(png1), Image.open(png2) size1, size2 = img1.size, img2.size if flag == 'lateral': # 横向 join_image = Image.new('RGB', (size1[0] + size2[0], size1[1])) # 创建一个2原图合并后大小的空白图 loc1, loc2 = (0, 0), (size1[0], 0) join_image.paste(img1, loc1) # 将原图1黏贴到指定位置 join_image.paste(img2, loc2) # 将原图2黏贴到指定位置 join_image.save(save_path) return save_path elif flag == 'vertical': # 纵向 join_image = Image.new('RGB', (size1[0], size1[1] + size2[1])) loc1, loc2 = (0, 0), (0, size1[1]) join_image.paste(img1, loc1) join_image.paste(img2, loc2) join_image.save(save_path) return save_path for i in range(1, 21): path = r".\拼图.png" if i == 11: path_up = None if path_up: if i > 11: path_up = image_join(path_up, path, save_path2) else: path_up = image_join(path_up, path, save_path1) else: path_up = path image_join(save_path1, save_path2, save_path3, flag='vertical')
原图片
拼接上
拼接下
完整