pythonpython-imaging-library

Draw text with background color


I want to know how can I draw text like this check image

As you can see text is on a green image and text has pink color background

My code, this is part of my code I'm using PIL

draw = ImageDraw.Draw(background)
font = ImageFont.truetype("assets/font2.ttf", 40)
font2 = ImageFont.truetype("assets/font2.ttf", 70)
arial = ImageFont.truetype("assets/font2.ttf", 30)
name_font = ImageFont.truetype("assets/font.ttf", 30)
para = textwrap.wrap(title, width=32)
j = 0
draw.text(
    (10, 10), f"{h}", fill="red", font=name_font
)
draw.text(
    (600, 150),
    "NOW PLAYING",
    fill="white",
    stroke_width=2,
    stroke_fill="white",
    font=font2,
)

Solution

  • You can use the draw.textbbox method to get a bounding box for your text string and fill it using the draw.rectangle method.

    from PIL import Image, ImageDraw, ImageFont
    
    image = Image.new("RGB", (500, 100), "white")
    font = ImageFont.truetype("segoeui.ttf", 40)
    draw = ImageDraw.Draw(image)
    position = (10, 10)
    text = "Hello world"
    
    bbox = draw.textbbox(position, text, font=font)
    draw.rectangle(bbox, fill="red")
    draw.text(position, text, font=font, fill="black")
    
    image.show()
    

    Example 1, black text on red rectangle

    If you want a larger margin for the background rectangle, you can adjust the returned bounding box like so:

    left, top, right, bottom = draw.textbbox(position, text, font=font)
    draw.rectangle((left-5, top-5, right+5, bottom+5), fill="red")
    draw.text(position, text, font=font, fill="black")
    

    Example 2, wider rectangle in background