PIL 字体居中显示,


# 导入需要的包
from PIL import Image, ImageDraw, ImageFont
import string
import os

# 背景尺寸
bg_size = (750, 1334)
# 生成一张尺寸为 750x1334 背景色为黄色的图片
bg = Image.new('RGB', bg_size, color=(255,255,0))

# 字体大小
font_size = 36
# 文字内容
text = '1lin24 is me. 我是1lin24。'

# 字体文件路径
font_path = os.path.join('.', 'fonts', 'SourceHanSansCN-Medium.otf')
# 设置字体
font = ImageFont.truetype(font_path, font_size)
# 计算使用该字体占据的空间
# 返回一个 tuple (width, height)
# 分别代表这行字占据的宽和高
text_width = font.getsize(text)
draw = ImageDraw.Draw(bg)

# 计算字体位置
text_coordinate = int((bg_size[0]-text_width[0])/2), int((bg_size[1]-text_width[1])/2)
# 写字
draw.text(text_coordinate, text,(0,0,0), font=font)

# 要保存图片的路径
img_path = os.path.join('.', 'output', 'center_text.jpg')
# 保存图片
bg.save(img_path)
print('保存成功 at {}'.format(img_path))

转载于:https://www.jianshu.com/p/8ba0c3e2381b

相关内容

    暂无相关文章

评论关闭