1. 程式人生 > 程式設計 >Python切割圖片成九宮格的示例程式碼

Python切割圖片成九宮格的示例程式碼

這篇文字講述如何使用Python把一張完整的大圖切割成9份小圖片,製作朋友圈九宮格圖文分享。

原圖如下:

Python切割圖片成九宮格的示例程式碼

我們想要利用這張圖製作高逼格的九宮格朋友圈分享。

達到類似於這樣的效果:

Python切割圖片成九宮格的示例程式碼

實現原理非常簡單,那就是利用PIL庫對原圖不斷畫小區域然後切下來儲存成新的小圖片。

假設每一個格子的寬和高分別是w、h,那麼第row行(從0開始計數),第col列(從0開始計數)的格子左上角座標和右下角座標分別是(col * w,row * h),(col * w + w,r * h + h)。

Python切割圖片成九宮格的示例程式碼

code snippet:
#! /usr/local/bin/python3
# -*- coding: utf-8 -*-
fromPILimportImage
defcut_image(image):
width,height = image.size
item_width = width /3.0
item_height = height /3.0
box_list = []
forrowinrange(0,3):
forcolinrange(0,3):
box = (col * item_width,row * item_height,( col +1) * item_width,( row +1) * item_height)
box_list.append( box )
image_list = [image.crop(box)forboxinbox_list]
returnimage_list
defsave_images(image_list):
dirName ='output'
ifFalse== os.path.exists( dirName ):
os.makedirs( dirName )
index =1
forimageinimage_list:
image.save(‘./output/python'+str(index) +'.png','PNG')
index +=1
if__name__ =='__main__':
image = Image.open("use.png")
image_list = cut_image(image)
save_images(image_list)

為了能在朋友圈中預覽時看到所有圖片的完整樣子,建議保證自己的原始圖片是正方形的,然後再執行這個指令碼,在output中得到九張圖片。最後,嗯,就可以去秀了!

總結

到此這篇關於Python切割圖片成九宮格的文章就介紹到這了,更多相關Python切割圖片 九宮格 內容請搜尋我們以前的文章或繼續瀏覽下面的相關文章希望大家以後多多支援我們!