Python切割圖片成九宮格的示例代碼
這篇文字講述如何使用Python把一張完整的大圖切割成9份小圖片,制作朋友圈九宮格圖文分享。
原圖如下:
我們想要利用這張圖制作高逼格的九宮格朋友圈分享。
達到類似于這樣的效果:
實現(xiàn)原理非常簡單,那就是利用PIL庫對原圖不斷畫小區(qū)域然后切下來存儲成新的小圖片。
假設每一個格子的寬和高分別是w、h,那么第row行(從0開始計數(shù)),第col列(從0開始計數(shù))的格子左上角坐標和右下角坐標分別是(col * w, row * h),(col * w + w, r * h + h)。
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切割圖片 九宮格 內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
用Python自動清理電腦內重復文件,只要10行代碼(自動腳本)
這篇文章主要介紹了用Python自動清理電腦內重復文件,只要10行代碼,本文給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下2021-01-01
python定時檢查啟動某個exe程序適合檢測exe是否掛了
定時檢查啟動某個exe程序這種情況下適合檢測某個exe程序是否掛了,感興趣的朋友可以了解下,希望本文對你有所幫助2013-01-01

