Predictive Hacks

Add Text On An Image using Python

add text to an image python

Let’s say that we want to create membership cards for our members. In this tutorial, we will show you how you can add text to images and then save them as a pdf ready to print.

Firstly, we will add some libraries and load our image.

import pandas as pd
import numpy as np

from PIL import Image
from PIL import ImageFont
from PIL import ImageDraw 

img ="card.jpg")
draw = ImageDraw.Draw(img)
Add Text On An Image using Python 1

Now, you have to set the font and the font size. Then in the draw text, you can add your text, its position, color as RGB, and many more options like align, etc.

Tip: If you are working in a server, you can set the font by adding the actual file of the font, e.g. arial.ttf

font = ImageFont.truetype("arial", 200)
draw.text((100, 100),"BILLY BONAROS",(0,0,0),font=font,align='left')
Add Text On An Image using Python 2

As you can see we need to fine tune the position so the text will be in the right place.

font = ImageFont.truetype("arial", 200)
draw.text((800, 680),"BILLY BONAROS",(0,0,0),font=font,align='left')
font = ImageFont.truetype("arial", 150)
draw.text((700, 1670),"1122",(0,0,0),font=font,align='left')
Add Text On An Image using Python 3

Batch add text, create and save images

Now that we know the right position for our text we can cretae cards for all of our members iterating over a dataframe of members.

members=pd.DataFrame({"name":['BILLY BONAROS','GEORGE PIPIS', 'GIULIA PENNI'],'id':['1111','1112','1113']})
            name    id
1   GEORGE PIPIS  1112
2   GIULIA PENNI  1113

We will create a function to takes as input a row and returns the final image.

def writer(row):
    img ="card.jpg")
    draw = ImageDraw.Draw(img)
    font = ImageFont.truetype("arial", 200)
    draw.text((800, 680),row['name'],(0,0,0),font=font,align='left')
    font = ImageFont.truetype("arial", 150)
    draw.text((700, 1670),row['id'],(0,0,0),font=font,align='left')

Now, we can iterate over the dataframe using list comprehention as follows

[writer(row).save(f"cards/{row['name']}.jpeg") for index,row in members.iterrows()]
Add Text On An Image using Python 4

Hack: Save them in one PDF

We want to save all membership cards in one pdf. We can do it using the library img2pdf.

import img2pdf

#get all files from the cards folder
arr = os.listdir('cards')
cards=[i for i in arr if i[-3:]=='peg']

#add the images to a pdf
with open("allcards.pdf", "wb") as f:
    f.write(img2pdf.convert([f"cards/{i}" for i in cards]))
Add Text On An Image using Python 5

Share This Post

Share on facebook
Share on linkedin
Share on twitter
Share on email

Leave a Comment

Subscribe To Our Newsletter

Get updates and learn from the best

More To Explore