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