#!/usr/bin/env python#coding=utf-8
importImageimportosimportsysimportglobimporttimeimportshutildefmerge_thumb(files, output_file):
imgs=[]
width=0
height=0
index=0#计算总宽度和长度
for file infiles:print ("file name : %s" %(str(file)))
img=Image.open(file)
imgs.append(img)if img.size[0] >width:
width=img.size[0]
height= img.size[1]#新建一个白色底的图片
merge_img = Image.new('RGB', (width, height), 0xffffff)for img inimgs:#把图片粘贴上去
merge_img.paste(img, (0, 0), img)
merge_img.save(output_file, quality=70)defgetPngName(filename):
begin= filename.index('thumbs/') + 7end= len(filename)- 4result=filename[begin:end]returnint(result)defcoverFiles(sourceFile, targetDir):
filename= os.path.split(sourceFile)[-1]
targetFile=os.path.join(targetDir,filename)ifos.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 notos.path.exists(THUMB_PATH):
os.makedirs(THUMB_PATH)
files= glob.glob(os.path.join(ROOT_PATH,'*.png'))for srcFile infiles:
targetFile= "thumbs/"+os.path.split(srcFile)[-1]
shutil.copy(srcFile,targetFile)
RESULT_PATH= os.path.join(THUMB_PATH, 'result')if notos.path.exists(RESULT_PATH):
os.makedirs(RESULT_PATH)
files= glob.glob(os.path.join(THUMB_PATH, '*.png'))
files_len=len(files)for i inrange(0,files_len):#合并图片
files = glob.glob(os.path.join(THUMB_PATH, '*.png'))
files_new=[]
index=0#print(files)
for file infiles:
files_new_len=len(files_new)
insert_index=0for j inrange(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 - 1begin= files_new[index].index('thumbs/') + 7end=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])