python - 如何使用 Python 中的 Pillow 在图片上添加单词并将其中一个加粗?
问题描述
我使用 Python 中的 PIL 库在图像上添加文本。如何在句子中加粗一个单词?假设我想在图片中写:“这是一个例句”。
解决方案
目前,您不能对句子的某些部分进行粗体、下划线、斜体等。您可以使用多个单独.text()
的命令并更改它们的 xy 坐标以使其看起来像一个句子。要加粗文本,您可以在字体系列中使用加粗文本字体,并将该字体用于.text()
命令。在下面的示例中,我使用了 Arial 和 Arial Bold 字体。我在 Windows 机器上,所以文件路径在 Linux 或 Mac 上会有所不同。
代码:
#import statements
import PIL
import PIL.Image as Image
import PIL.ImageDraw as ImageDraw
import PIL.ImageFont as ImageFont
#save fonts
font_fname = '/fonts/Arial/arial.ttf'
font_fname_bold = '/fonts/Arial/arialbd.ttf'
font_size = 25
#regular font
font = ImageFont.truetype(font_fname, font_size)
#bolded font
font_bold = ImageFont.truetype(font_fname_bold, font_size)
#Open test image. Make sure it is in the same working directory!
with Image.open("test.jpg") as img:
#Create object to draw on
draw = ImageDraw.Draw(img)
#Add text
draw.text(xy=(10,10),text="Gardens have ",font=font)
draw.text(xy=(175,10),text="many",font=font_bold)
draw.text(xy=(240,10),text=" plants and flowers",font=font)
#Display new image
img.show()
测试图像:
推荐阅读
- javascript - 如何设置 WordPress 和 WooCommerce API,以便在发布时不会出现 CORS 错误?
- autodesk-forge - 使用 Auto-desk Forge 实现登录系统
- python - 使用 pymongo 将数据插入 mongo 时删除 NaT 值
- c - 我的插座游戏有一些问题,我不明白为什么
- debian - Snort 规则配置问题
- python - 如何使用 BeautifulSoup 通过类似的 HTML 块“循环”?
- html - 推文后重定向 - 通过网站的 twitter 实现共享
- javascript - 在Javascript中,所有小数点都是奇数吗?
- sql - SQLite3 代码动态插入要删除的行数据的列值
- matlab - Matlab 2017:在标记的二进制图像中,用不同颜色填充斑点