前言:在圖片中繪制文字內容,如果希望文字內容居中繪制,就需要獲取文字的大小和圖片的大小結合做出調整
import pil
# 話不多說直接上代碼👇
# 首先我們需要一張圖片(自己創建圖片也可以)
path = "./pic/luxunshuo/002.png"
bg = Image.open(path)
draw = ImageDraw.Draw(bg) # 創建可以在給定圖像上繪圖的對象
text = '烏拉!' # 文字內容
size = 25 # 文字大小
color = (252,252,252) # 文字顏色
font = './ttf/青鳥華光簡魏體字體.ttf' # 字體格式設置(可以自己下載ttf格式字體)
font = ImageFont.truetype(font,size) # 加載字體格式和字體大小
# ---------------------------------------------------------------------------
x0,y0 = bg.size # 獲得圖片的大小
ascent, descent = font.getsize(text) # 這里拿到文字內容的大小
x = x0/2-ascent/2 # 這里是文字內容的居中繪制算法
y = 230 # y坐標也可以根據x算法設置居中顯示(y0/2-descent/2),我這里是自定義
draw.text((x,y),text,color,font = font) # 繪制 文字坐標 文字內容 顏色 字體
bg.show()