PIL(Python Imaging Library)是一個很是強大的Python庫,可是它支持Python2.X, 在Python3中則使用的是Pillow庫,它是從PIL中fork出來的一個分支。提供了很是強大的圖片處理能力,包括存儲、格式轉換、圖像處理等操做程序員
有時候看到朋友圈的九宮格動態,是否是感受很是有逼格呢? 今天就用Python來實現九宮格切圖。app
先來看幾張效果圖函數
大體思路分爲如下幾步spa
讀取初始照片code
比較照片的寬高,數值較大的做爲邊長生成一個新的空白圖片blog
將初始圖片粘貼至第二部建立的空白圖片上圖片
將圖片進行切割ip
保存圖片處理
直接上代碼it
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文件的下載連接。