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