PIL的ImageFont输出中文

发布时间 2023-09-08 14:27:02作者: 海_纳百川

先上代码:

from PIL import Image, ImageDraw, ImageFont

# 创建一张空白图像
image = Image.new("RGB", (500, 500), "white")

# 获取中文字体文件(替换为你的字体文件路径)
chinese_font = ImageFont.truetype("path/to/your/chinese/font.ttf", size=36)

# 创建 draw 对象
draw = ImageDraw.Draw(image)

# 在图像上绘制中文字符
text = "你好,世界!"
draw.text((100, 100), text, fill="black", font=chinese_font)

# 保存图像
image.save("output.png")

以上代码的前提是你要有这个tiff字体,使用以下命令看看你的linux中有哪些中文字体,linux的中文字体正常情况下都存在/usr/share/fonts/truetype

fc-list :lang=zh

如果上个命令没有中文字体输出,那么就需要从别处拷贝或者下载中文字体,放到/usr/share/fonts/truetype中,然后执行以下命令更新字体

fc-cache -f -v