In this blog post, I will be showing how to add text to an image in Python.
I used this code to generate hundreds of images with different text for one of our clients.
The full script is downloadable at the bottom with the required extras.
Firstly, install the Python library Pillow.
Pillow is a PIL fork, install Pillow using pip and import PIL into the Python script.
In Python, select the image that you would like to use. In this post I’ll be using an image of the world.
This image is saved in the same folder as the script, therefore only the filename is required to reference it.
The next step is to pick the font for the text, in this blog post I chose Amaranth.
To use a font we require a .ttf or .otf file. https://www.wfonts.com/ is a good website to get these files from, download it and save it into the folder with the script and image.
Following this, customise the text. We can choose: the text, its position, its font and its colour.
Yellow – This is the position of the text (x,y).
Red – This is the text that will be displayed.
Green – This is the font we defined earlier on; different text can be in different fonts.
Blue – This is the colour of the text using RGBA
The final step is to combine our image and text.
We can then show the image as well as saving it, this is our new image.
To automate this to create several images, put this code into a for loop and for each iteration modify the inputs for that image. Make sure to save each file with a different filename. Here is an example:
The 1st script without the loop can be downloaded here with the font file and base image – Image with Text Generator
The 2nd script with the loop can be downloaded here with the font file and base image – Image with Text Generator – Loop