Skip to content

Commit 98278dc

Browse files
committed
利用PIL实现图片切割
1 parent 5bc2431 commit 98278dc

File tree

13 files changed

+67
-1
lines changed

13 files changed

+67
-1
lines changed

PythonDemo/PIL/alice_color.png

407 KB
Loading

PythonDemo/PIL/cutImage.py

Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
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)
Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
# -*- coding: utf-8 -*-
2+
"""
3+
使用 Image 类
4+
"""
5+
6+
from PIL import Image
7+
im = Image.open("alice_color.png")
8+
#format 这个属性标识了图像来源
9+
#size属性是一个二元tuple,(600, 800):宽:600px,高:800px
10+
# mode 属性定义了图像bands的数量和名称,以及像素类型和深度。常见的modes 有 “L” (luminance) 表示灰度图像, “RGB” 表示真彩色图像, and “CMYK” 表示出版图像。
11+
print(im.format, im.size, im.mode)#PNG (600, 800) RGBA
12+
im.show()#显示图像

PythonDemo/PIL/result/python1.png

1.49 KB
Loading

PythonDemo/PIL/result/python2.png

79 KB
Loading

PythonDemo/PIL/result/python3.png

854 Bytes
Loading

PythonDemo/PIL/result/python4.png

11.1 KB
Loading

PythonDemo/PIL/result/python5.png

126 KB
Loading

PythonDemo/PIL/result/python6.png

1.2 KB
Loading

PythonDemo/PIL/result/python7.png

35.6 KB
Loading

0 commit comments

Comments
 (0)