from PIL import Image
import os
def fill_images(image):
width, height = image.size
side = max(width, height)
new_image = Image.new(image.mode, (side, side), color='white')
if width > height:
new_image.paste(image, (0, int((side - height ) /2)))
else:
new_image.paste(image, (int((side - width) / 2), 0))
return new_image
def cut_images(image):
width, height = image.size
one_third_width = int(width / 3)
box_list = []
for x in range(3):
for y in range(3):
left = x * one_third_width
upper = y * one_third_width
right = (x + 1) * one_third_width
lower = (y + 1) * one_third_width
box = (left, upper, right, lower)
box_list.append(box)
image_list = [image.crop(box) for box in box_list]
return image_list
def save_images(image_list):
ouput_path = os.path.abspath(os.path.dirname(__file__))
for index, image in enumerate(image_list):
image.save(f"{output_path}/{index + 1}.png", "PNG")
def run():
input_path = input('请输入图片的路径:\n' )
image = Image.open(input_path)
image = fill_images(image)
image_list = cut_images(image)
save_images(image_list)
if name == '__main__':
run()
保存图片的代码改为:image.save(ouput_path+"/%s.png"%(index+1), "PNG")