羡慕朋友圈九宫格图片?Python五步完成,助你发一个炫酷的朋友圈~
原图(love.jpg)
九宫格朋友圈效果图
实现步骤
(编译器我最近特别喜欢用jupyter notebook,可以分步查看效果,缺点不能像pycharm给提示)
第一步,引用Image库,全程也只用这个库
from PIL import Image
第二步,打开图片
image = Image.open(r'C:\Users\Administrator\Desktop\love.jpg')
第三步,图片优化成正方形居中
width,height = image.size
new_size = width if width > height else height
new_image = Image.new(image.mode,(new_size,new_size),color = 'white')
if width > height:
new_image.paste(image,(0, int((new_size - height) / 2)))
else:
new_image.paste(image,(int((new_size - width) / 2),0))
new_image
第四步,切图,关键,new_image.crop(box)
item_width = int(new_size / 3)
box_list = []
for i in range(0,3):
#两重循环,生成9张图片基于原图的位置
for j in range(0,3):
box = (j * item_width,i * item_width,(j +1)* item_width,(i+1)*item_width)
#print((j * item_width,i * item_width,(j +1)* item_width,(i+1)*item_width))
box_list.append(box)
第五步,保存图片
image_list = [new_image.crop(box) for box in box_list]
#image_list[4].show()
i = 1
for image in image_list:
image.save(r'C:\Users\Administrator\Desktop\love\{}.jpg'.format(i))
i += 1
欢迎留言讨论,一起学python
领取专属 10元无门槛券
私享最新 技术干货