Python 如何使用 Pillow 在图片上添加文字并加粗其中一个文字?
How to add words on a picture and bold one of them using Pillow in Python?
我在 Python 中使用 PIL 库在图像上添加文本。如何加粗句子中的一个词?假设我想在图片中写下:“This is an example sentence”。
目前,您不能对句子的某些部分进行粗体、下划线、斜体等操作。您可以使用多个单独的 .text()
命令并更改它们的 x-y 坐标,使其看起来像一个句子。要加粗文本,您可以使用字体系列中的加粗文本字体,并将该字体用于 .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
我在 Python 中使用 PIL 库在图像上添加文本。如何加粗句子中的一个词?假设我想在图片中写下:“This is an example sentence”。
目前,您不能对句子的某些部分进行粗体、下划线、斜体等操作。您可以使用多个单独的 .text()
命令并更改它们的 x-y 坐标,使其看起来像一个句子。要加粗文本,您可以使用字体系列中的加粗文本字体,并将该字体用于 .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