Python 蟒蛇,皮尔;文本到图像和字体

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15857117/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 21:11:06  来源:igfitidea点击:

Python, PIL; Text to Image and fonts

pythonimagetextpython-imaging-librarybold

提问by Harry Lime

I have an issue with writing text to an image under Python and PIL - I'm able to write text to a png file, though not bold text. Could anyone provide an example of how to achieve this?

我在 Python 和 PIL 下将文本写入图像时遇到问题 - 我能够将文本写入 png 文件,但不是粗体文本。谁能提供一个如何实现这一目标的例子?

I thought the easiest solution may bewas use a bold-variant of a text, but I'm unable to see anything in the Windows/font folder that supplies this - does this mean font types have a 'bold attribute' that is T/F?:
quick look for bold-fonts under windows

我认为最简单的解决方案可能是使用文本的粗体变体,但我无法在 Windows/font 文件夹中看到任何提供此内容的内容 - 这是否意味着字体类型具有一个“粗体属性”,即 T/ F?:
在 windows 下快速查找粗体

Code I'm using:

我正在使用的代码:

import PIL
from PIL import ImageFont
from PIL import Image
from PIL import ImageDraw

# font = ImageFont.truetype("Arial-Bold.ttf",14)
font = ImageFont.truetype("Arial.ttf",14)
img=Image.new("RGBA", (500,250),(255,255,255))
draw = ImageDraw.Draw(img)
draw.text((0, 0),"This is a test",(0,0,0),font=font)
draw = ImageDraw.Draw(img)
img.save("a_test.png")

采纳答案by Pavel Anossov

You aren't looking at actual font files in the control panel (explorer magically turns into the font viewer control panel when in the Windows/fonts folder as well), they are grouped by family for your convenience. Double click the family to see the fonts in the family:

您不是在控制面板中查看实际的字体文件(在 Windows/fonts 文件夹中时,资源管理器也神奇地变成了字体查看器控制面板),为了您的方便,它们按系列分组。双击族可以查看族中的字体:

enter image description here

在此处输入图片说明

Then right-click and choose properties to find the file name:

然后右键单击并选择属性以查找文件名:

enter image description here

在此处输入图片说明

回答by snow

A simple way to do it:

一个简单的方法:

font = ImageFont.load_default().font

Also you can do a google search for 'verdana.ttf'and download it put it in the same directory as the python file:

您也可以在谷歌上搜索“verdana.ttf”并将其下载到与 python 文件相同的目录中:

Then add it like this:

然后像这样添加它:

font = ImageFont.truetype("Verdana.ttf",14)