這篇文字講述如何使用Python把一張完整的大圖切割成9份小圖片,製作朋友圈九宮格圖文分享。
原圖如下:
我們想要利用這張圖製作高逼格的九宮格朋友圈分享。
達到類似於這樣的效果:
[外鏈圖片轉存失敗,源站可能有防盜鏈機制,建議將圖片保存下來直接上傳(img-gtn8DITU-1588081268709)(https://upload-images.jianshu.io/upload_images/22699699-57ef2ecc5e543252.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)]
實現原理非常簡單,那就是利用PIL庫對原圖不斷畫小區域然後切下來存儲成新的小圖片。
假設每一個格子的寬和高分別是w、h,那麼第row行(從0開始計數),第col列(從0開始計數)的格子左上角座標和右下角座標分別是(col * w, row * h),(col * w + w, r * h + h)。
在學習過程中有什麼不懂得可以加我的
python學習qun,855408893
羣裏有不錯的學習視頻教程、開發工具與電子書籍。
與你分享python企業當下人才需求及怎麼從零基礎學習好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中得到九張圖片。最後,嗯,就可以去秀了!