import os
from PIL import Image
def cut_image(image,ww,hh):
width, height = image.size
item_width = int(width / ww)
item_height = int(height / hh)
box_list = []
# (left, upper, right, lower)
for i in range(0,hh):
for j in range(0,ww):
box = (j*item_width,i*item_height,(j+1)*item_width,(i+1)*item_height)
box_list.append(box)
image_list = [image.crop(box) for box in box_list]
return image_list
#已经拆分完,等待输出的图片
def save_images(imf,image_list):
image = Image.open(imf)
width, height = image.size
index = 0
x = 0
y = 0
# 产生一张空白图
new_img = Image.new('RGB', (width, height), 255)
image_list.reverse()
for image in image_list:
new_img.paste(image, (x, y))
y+=height//10
index += 1
if index==1 :y+=9
new_img.save('x'+imf)
# os.remove(imf)
def start(items, size, first_path=None):
#批量获取图片路径
try:
for image in items:
print(os.path.basename(image))
file_path = os.path.basename(image) #图片保存的地址
image = Image.open(file_path)
image_list = cut_image(image,1,10)#列,行
save_images(file_path,image_list)
except:
pass
path = './' # 图片文件夹路径
def getAllImg(path):
result = []
filelist = os.listdir(path)
for file in filelist:
if os.path.isfile(os.path.join(path, file)):
if file.split('.')[1] in ('jpg', 'png'):
result.append(os.path.join(path, file))
return result
if __name__ == '__main__':
s = getAllImg(path)
s.sort()
start(s, 0)
正文完