Python切图九宫格

 1 # -*- coding: utf-8 -*-
 2 '''
 3 将一张图片填充为正方形后切为9张图
 4 '''
 5 from PIL import Image
 6 import sys
 7 #将图片填充为正方形
 8 def fill_image(image):
 9     width, height = image.size
10     #选取长和宽中较大值作为新图片的
11     new_image_length = width if width > height else height
12     #生成新图片[白底]
13     new_image = Image.new(image.mode, (new_image_length, new_image_length), color='white')
14     #将之前的图粘贴在新图上,居中
15     if width > height:#原图宽大于高,则填充图片的竖直维度
16         #(x,y)二元组表示粘贴上图相对下图的起始位置
17         new_image.paste(image, (0, int((new_image_length - height) / 2)))
18     else:
19         new_image.paste(image, (int((new_image_length - width) / 2),0))
20     return new_image
21 #切图
22 def cut_image(image):
23     width, height = image.size
24     item_width = int(width / 3)
25     box_list = []
26     # (left, upper, right, lower)
27     for i in range(0,3):#两重循环,生成9张图片基于原图的位置
28         for j in range(0,3):
29             #print((i*item_width,j*item_width,(i+1)*item_width,(j+1)*item_width))
30             box = (j*item_width,i*item_width,(j+1)*item_width,(i+1)*item_width)
31             box_list.append(box)
32 
33     image_list = [image.crop(box) for box in box_list]
34     return image_list
35 #保存
36 def save_images(image_list):
37     index = 1
38     for image in image_list:
39         image.save('./python'+str(index) + '.png', 'PNG')
40         index += 1
41 
42 if __name__ == '__main__':
43     file_path = "python.jpeg"
44     image = Image.open(file_path)
45     #image.show()
46     image = fill_image(image)
47     image_list = cut_image(image)
48     save_images(image_list)

    

    

    

posted @ 2019-01-11 11:25  幽灵鸟  阅读(891)  评论(0编辑  收藏  举报