首页 > 解决方案 > 如何使用 Python 中的 Pillow 在图片上添加单词并将其中一个加粗?

问题描述

我使用 Python 中的 PIL 库在图像上添加文本。如何在句子中加粗一个单词?假设我想在图片中写:“这是一个例句”。

标签: pythonpython-imaging-library

解决方案


目前,您不能对句子的某些部分进行粗体、下划线、斜体等。您可以使用多个单独.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()

测试图像:

https://i.stack.imgur.com/zU75J.jpg


推荐阅读