Reputation: 3
I add text on the image using PIL library in Python. How can I bold one word in a sentence? Let's say I want to write in the picture: "This is an example sentence".
Upvotes: 0
Views: 2324
Reputation: 2859
Currently, you can't bold, underline, italicize etc. certain parts of a sentence. You can use multiple separate .text()
commands and change their x-y coordinates to make it look like one sentence. To bold text, you can use a bolded text font in a font family, and use that font for a .text()
command. In the example below, I used the Arial and the Arial Bold font. I am on a windows machine, so the file paths will be different on Linux or Mac.
Code:
#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()
Test image:
https://i.sstatic.net/zU75J.jpg
Upvotes: 1