用Python搞定九宮格式的朋友圈。內附“馬雲”朋友圈
PIL(Python Imaging Library)是一個非常強大的Python庫,但是它支援Python2.X, 在Python3中則使用的是Pillow庫,它是從PIL中fork出來的一個分支。提供了非常強大的圖片處理能力,包括儲存、格式轉換、影象處理等操作
有時候看到朋友圈的九宮格動態,是不是感覺非常有逼格呢? 今天就用Python來實現九宮格切圖。
先來看幾張效果圖
大致思路分為以下幾步
-
讀取初始照片
-
比較照片的寬高,數值較大的作為邊長生成一個新的空白圖片
-
將初始圖片貼上至第二部建立的空白圖片上
-
將圖片進行切割
-
儲存
直接上程式碼
from PIL import Image image = Image.open('圖片路徑.jpg') width, height = image.size #高和寬進行比較,較大的為新圖片的長度 new_length = height if height > width else width # 建立一張正方形空圖片,底色為白色, new_image = Image.new(image.mode, (new_length, new_length), color='white') # 將要處理的圖片貼上到新建立的圖片上,居中 if height > width: # 如果高度大於寬,則填充圖片的寬度 new_image.paste(image, (int((new_length - width) / 2)), 0) else: new_image.paste(image, (0, int((new_length - height) / 2))) # 朋友圈一排三張圖片因此寬度切割成3份 new_length = int(new_length / 3) # 用來儲存每一個切圖 box_list = [] for i in range(0, 3): for j in range(0, 3): # 確定每個圖片的位置 box = (j * new_length, i * new_length, (j + 1) * new_length, (i + 1) * new_length)# (left, top, right, bottom) box_list.append(box) # 通過crop函式對圖片進行切割 image_list = [new_image.crop(box) for box in box_list] for (index, image) in enumerate(image_list): image.save(str(index) + '.png', 'PNG') print("九宮格圖片生成完畢!")
為了方便使用,通過pyinstaller對指令碼進行打包成exe檔案。
pip3 install pyinstaller
執行
pyinstaller -F cut_picture.py
就會在當前目錄生成一個dist資料夾,裡面就有我們最終需要的exe檔案。如何使用呢?只需要在將要切割的圖片重新命名為“a.jpg”,放入同級目錄中,雙擊啟動即可
效果圖如下
有需要的同學可以在公眾號【程式設計師共成長】後臺 回覆【 cut 】獲取exe檔案的下載連結。