from PIL import Image from PIL import ImageFont from PIL import ImageDraw import glob import os class MergePIC: def __init__(self, row = 1, col = 1, pages = 1): self.row = row self.col = col self.pages = pages def domerge(self, headname, outname): #find size in a pic im1 = Image.open(headname) im_w, im_h = im1.size #creat new img size fit row, col new_img = Image.new('RGB', (im_w*self.col+1, im_h*self.row+1), (255, 255, 255)) #get head num headnum = int(headname.split("_")[1][:3]) endnum = headnum + self.row*self.col pastname = headname # print(type(self.row) == type(1), self.row, self.col) for i in range(0,self.row): for k in range(0,self.col): new_img.paste(im1, (0+(k*im_w), 0+(i*im_h))) if headnum < endnum: headnum += 1 str_head = "%03d" % headnum pastname = headname.split("_")[0] + "_" + str_head + ".jpg" if os.path.exists(pastname) == False: print("unable to past %s \n please check file" % pastname) im1 = Image.new('RGB', (im_w, im_h), (255, 255, 255)) elif headnum > self.pages: print("%s num is %d, out of need pages %d" % (pastname, headnum, self.pages)) im1 = Image.new('RGB', (im_w, im_h), (255, 255, 255)) else: im1 = Image.open(pastname) #save the img #fullFile = outname + "_" + headname.split("_")[1] #new_img.save(fullFile) new_img.save(outname) def pastPIC(self, inname, i, k): pass # new_img.paste(inname, (0, 60)) def listPIC(self, dir): self.files = glob.glob(dir+"full*.jpg") #check files and number print("== check file full ==") print("Your files all : %s \nYour request is : %d" % (len(self.files), self.pages)) if len(self.files) == self.pages: print("check page num pass") else: print("Please confirm the number of files again") # for i in range(0,self.pages): # print(self.files[i][2::]) def doloop(self): num = 1 for i in range(0, self.pages, self.row*self.col): inname = self.files[i][2::] outnum = inname.split("_")[0][-3::] str_i = "%03d" % num num += 1 outname = "merge" + outnum + "_" + str_i + ".jpg" self.domerge(inname, outname) if __name__ == '__main__': foo = MergePIC(2,4,140) foo.listPIC("./") foo.doloop()