"""
思路:
1、转换为正方形
2、切割小图片的尺寸要保持一致
3、计算小图片的坐标值
4、图片有几个坐标 —— 4个
"""
from PIL import Image
# 1、填充图像为正方形
def fill_image(img):
width, height = img.size
# 原图 分割之后的图
# 选择最大的宽和高 作为新图像的宽和高
new_image_length = width if width > height else height
# 创建新的图像
new_image = Image.new(img.mode, (new_image_length, new_image_length), color='white')
if width > height:
# 拼贴、粘贴
new_image.paste(img, (0, int(new_image_length - height)/2))
else:
new_image.paste(img, (int((new_image_length - width) / 2), 0))
return new_image
# 2、分割、裁剪图像
def split_image(img):
width, height = img.size
item_width = int(width/3)
box_list = []
# 循环嵌套
for x in range(0, 3):
for y in range(0, 3):
# 左下右上 - 4元组坐标
box = (y*item_width, x*item_width, (y+1)*item_width, (x+1)*item_width)
box_list.append(box)
# 裁剪
img_list = [img.crop(box) for box in box_list]
return img_list
# 3、保存裁剪之后图像
def save_image(img_list):
index = 1
for img in img_list:
img.save('picture/'+str(index)+'.png')
index += 1
if __name__ == '__main__':
# 打开一张图片
image = Image.open('picture/gakki.png')
image = fill_image(image)
img_list = split_image(image)
save_image(img_list)
运行后的9张图片: