Python – Use PIL to write text on top of another image

Use PIL to write text on top of another image… here is a solution to the problem.

Use PIL to write text on top of another image

from PIL import Image, ImageDraw, ImageFont, ImageOps

Command:

    font1 = ImageFont.truetype('timesbd.ttf',17)

backgtound = Image.open('plan.png')
    bar = Image.open("bar.png")
    write = ImageDraw.Draw(bar)
    write.text(xy=(73, 181), text="{} / 20".format(numbertotal), fill=(255, 255, 255), font=font1)
    background.paste(bar, (2, 173), bar)
    background.save('plan2.png')

I have a picture named “bar” on a picture named “plan”,

I want to write a paragraph on the picture “bar”, but the text is not on the second picture, only the first picture one, can someone help me? (x,y coordinates are correct).

Solution

IIUC, and you want the text to be above the image bar, the problem is that you write the text after pasting. Instead, you can write your text on the image bar first and paste it into background.

In this example, plan.png is a dog and bar.png is a cat. You can see that the text is above bar, not above plan:

font1 = ImageFont.truetype('timesbd.ttf',17)

background = Image.open('plan.png')
bar = Image.open("bar.png")
write = ImageDraw.Draw(bar)
write.text(xy=(79, 181), text="my text", fill=(255, 255, 255), font=font1)
background.paste(bar)
background.save('plan2.png')

enter image description here

Related Problems and Solutions