以下是为郭景霞写的拼图片小脚本
# -*- coding: utf-8 -*-
import sys
reload(sys)
sys.setdefaultencoding('utf-8')
import os
import math
from PIL import Image,ImageDraw,ImageFont
if __name__ == '__main__' :
path = 'D:/Recombination/inputImg/'
pall,xyRatio = [], []
for i in os.listdir(path):
im=Image.open(path+i)
(x,y) = im.size
pall.append(im.size)
xyRatio.append(x/(1.00000*y))
if abs(1.*max(xyRatio)/(1.*min(xyRatio))-1)> 0.05:
print '横竖比差异超过5%,影响整体拼图效果,本次退出。请重新调整尺寸'
sys.exit()
HorW=(raw_input("请输入你的排版方式,H竖向,W横向 H or W ?,然后回车\n")).lower()
#perRowCount 为每行多少字
perRowCount=int(raw_input("请输入该方向需要多少张图,然后回车\n"))
#fileCount为多少文件数
fileCount= len(pall)
#print perRowCount,fileCount,int(math.ceil(fileCount*1.00/int(perRowCount)))
xlist,ylist = [],[]
for xsize , ysize in pall :
ylist.append(ysize)
xlist.append(xsize)
#ymin ,xmin 文件中高宽的最小值
ymin ,xmin = min(ylist),min(xlist)
if HorW == 'h':
times = 0
#rowCount为多少行数
rowCount = int(math.ceil(fileCount*1.0000/perRowCount))
#设置生成的新图片尺寸大小
newImg = Image.new("RGBA",(xmin*rowCount,ymin*perRowCount),(217,214,203))
rowCount_times = rowCount
for i in os.listdir(path):
print i ,times
imgFrom = Image.open(path + i)
imgFrom = imgFrom.resize((xmin,ymin))
if((times%perRowCount == 0) ):
rowCount_times = rowCount_times - 1
y1 = ymin *(1+ times%perRowCount)
y0 = ymin *(0+ times%perRowCount)
x1 = (rowCount_times+1) * xmin
x0 = (rowCount_times+0) * xmin
newImg.paste(imgFrom.crop((0,0,xmin,ymin)),(x0,y0,x1,y1))
times += 1
if HorW == 'w':
#colstep 第x列,
colstep = perRowCount
times = 0
#rowCount为多少行数
rowCount = int(math.ceil(fileCount*1.0000/perRowCount))
#设置生成的新图片尺寸大小
newImg = Image.new("RGBA",(xmin*perRowCount ,ymin*rowCount),(217,214,203))
for i in os.listdir(path):
print i
imgFrom = Image.open(path + i)
imgFrom = imgFrom.resize((xmin,ymin))
colstep = times/perRowCount
y1 = (colstep+1) * ymin
x1 = (perRowCount -times%perRowCount) * xmin
y0 = (colstep+0) * ymin
x0 = (perRowCount -times%perRowCount-1) * xmin
#newImg.paste(imgFrom.crop((0,0,xmin,ymin)),(0,0,xmin,ymin))
print x0,y0,x1,y1
newImg.paste(imgFrom.crop((0,0,xmin,ymin)),(x0,y0,x1,y1))
times += 1
newImg.show()
newImg.save("D:/Recombination/ImgnewImg.png","PNG")