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文件的下載鏈接。