import os
import cv2
import numpy as np
from PIL import Image, ImageDraw, ImageFont
txtList = ["保存单帧", "保存多帧"]
height = 300
width = 1068
# word = word.decode('utf-8') # 这里吧文本就是编下码, 有时候从数据库中拿出来的数据写入的时候会乱码
# 使用ImageFout.truetype("字体", "文字大小(像素px)")
SimHei = "/usr/share/fonts/truetype/wqy/wqy-zenhei.ttc" # 一个字体文件
font = ImageFont.truetype(SimHei, size=200) # 设置字体和大小
for txt in txtList:
fusion = Image.new('RGB', (width, height ), color=(50,50,50)) # 背景图像
# 计算出要写入的文字占用的像素
w, h = font.getsize(txt) # 字体宽高
print("(%d, %d)"%( w,h))
print("sub (%d, %d)"%( width-w,height-h))
print("(%d, %d)"%(int((width-w)/2), int((height-h)/2)))
# 创建一个可以在给定图像上绘图的对象
draw = ImageDraw.Draw(fusion)
# draw.text(((width-w)/2, (height-h)/2), txt, fill="white", font=font)
draw.text((int((width-w)/2), int((height-h)/4)), txt, fill="white", font=font)
# ImageDraw.Draw.text(xy, text, fill=None, font=None, anchor=None, spacing=0, align=”left”)
# draw.text((5, 5), txt, font = font, fill ="white", align ="right")
bbox = draw.textbbox((int((width-w)/2), int((height-h)/2)), txt, font=font)
# draw.rectangle(bbox, outline="red")
print(bbox)
# 保存画布
fusion.save(txt+".png" ,"PNG")
# fusion.show()
# break
# break
标签:int,font,python,draw,height,width,中文字体,txt,pillow
From: https://www.cnblogs.com/xiaohuidi/p/17022871.html