因项目需求需要将图片合并故写了一个python脚本,在这里放个笔记
#!/usr/bin/env python #coding=utf-8 import Image import os import sys import glob import time import shutil def merge_thumb(files, output_file): imgs = [] width = 0 height = 0 index = 0 # 计算总宽度和长度 for file in files: print ("file name : %s" % (str(file))) img = Image.open(file) imgs.append(img) if img.size[0] > width = img.size[0] height = img.size[1] # 新建一个白色底的图片 merge_img = Image.new('RGB', (width, height), 0xffffff) for img in imgs: # 把图片粘贴上去 merge_img.paste(img, (0, 0), img) merge_img.save(output_file, quality=70) def getPngName(filename): begin = filename.index('thumbs/') + 7 end = len(filename)- 4 result = filename[begin:end] return int(result) def coverFiles(sourceFile, targetDir): filename = os.path.split(sourceFile)[-1] targetFile = os.path.join(targetDir,filename) if os.path.isfile(sourceFile): open(targetFile, "wb").write(open(sourceFile, "rb").read()) if __name__ == '__main__': ROOT_PATH = os.path.abspath(os.path.dirname(__file__)) #IMG_PATH = os.path.join(ROOT_PATH, 'img') THUMB_PATH = os.path.join(ROOT_PATH, 'thumbs') print ("thumb_path:%s" % str(THUMB_PATH)) if not os.path.exists(THUMB_PATH): os.makedirs(THUMB_PATH) files = glob.glob(os.path.join(ROOT_PATH,'*.png')) for srcFile in files: targetFile = "thumbs/"+os.path.split(srcFile)[-1] shutil.copy(srcFile,targetFile) RESULT_PATH = os.path.join(THUMB_PATH, 'result') if not os.path.exists(RESULT_PATH): os.makedirs(RESULT_PATH) files = glob.glob(os.path.join(THUMB_PATH, '*.png')) files_len = len(files) for i in range(0,files_len): # 合并图片 files = glob.glob(os.path.join(THUMB_PATH, '*.png')) files_new = [] index = 0 #print(files) for file in files: files_new_len = len(files_new) insert_index = 0 for j in range(0,files_new_len): if (getPngName(files_new[j])>getPngName(files[index])): insert_index = j+1; files_new.insert(insert_index,file) index += 1 #get put out file name index = len(files) - len(files_new) index = len(files_new) - index - 1 begin = files_new[index].index('thumbs/') + 7 end = len(files_new[index]) output = 'result/'+files_new[index][begin:end] print ('output=%s index = %s' % (output,index)) merge_output = os.path.join(THUMB_PATH, output) begin_time = time.clock() merge_thumb(files_new, merge_output) end_time = time.clock() print ('merge_thumb time:%s**********output:%s*******remove:%s' % (str(end_time - begin_time),output,files_new[index])) os.remove(files_new[index])
我所做的事情是讲一个文件夹下面的所有图片如(1.png 2.png ... 10.png)按照一定规律合并
合并规律为1-10合并为1.png 2-10合并为2.png 以此类推