看到朋友圈中發九宮格的朋友圈,感覺很炫酷,自己也想去弄一下,可是又懶得下各種工具,又懶得手動裁剪。沒辦法只好自己動手,使用Python寫一套邏輯進行自動裁剪。廢話不多說,請看正文:
安裝依賴
pip3 install pillow
完整代碼
import os
from PIL import Image
class ImageCrop(object):
def __init__(self, img_path):
"""
初始化
:param img_path: 要切割的圖片
"""
self.img_path = img_path
def crop(self):
"""
切割
:return:
"""
im = Image.open(self.img_path)
width, height = im.size
w = width / 3
h = height / 3
for y in range(3):
for x in range(3):
image = im.crop(box=(x * w, y * h, (x + 1) * w, (y + 1) * h))
path = os.path.join(os.getcwd(), "images", "{}_{}.png".format(x, y))
image.save(path)
if __name__ == '__main__':
ic = ImageCrop(img_path="onepiece.png")
ic.crop()
原圖如下:
切割之後發朋友圈效果如下:
自此,Over~~~