If you need to add text to image then you can do so in various ways. In fact, python is also an excellent language to perform this task. It provides the feature-rich Python Image Library (PIL) for image editing. In this article, we will learn how to add text to image in Python using PIL.
How to Add Text to Image in Python
Here are the steps to add text to image in Python.
1. Import PIL
First we will import PIL library into our code.
#!usr/bin/env from PIL import Image from PIL import ImageDraw
2. Open Image
Next, we open image, say, /home/ubuntu/image.jpg. For this purpose, we use open() function from Image module imported above.
img = Image.open('/home/ubuntu/image.png')
3. Add Text to Image
Next, we call draw() method to add text to our image.
I1 = ImageDraw.Draw(img)
We call text() method on the I1 object to add text ‘hello world’.
I1.text((28, 36), "hello world", fill=(255, 0, 0))
Here is the syntax of text() function.
text( (x,y), Text, font, fill) Parameters: (x, y): offset(in pixels)/coordinate where you want to add text Text: Text or message to be added Font: font type and font size of the text. Fill: Font color to your text.
Of course, you can customize the text as per your requirement. For example, you can change (x,y) value in text function to change the position of image. In the above example, we have skipped the font argument. But you can always customize font style as shown below using ImageFont module in PIL.
from PIL import ImageFont myFont = ImageFont.truetype('OpenSans.ttf', 65) # Add Text to an image I1.text((10, 10), "hello world", font=myFont, fill =(255, 0, 0))
4. Save Image
Now that you have made the changes to image, save it with save() command.
img.save("/home/ubuntu/image.png")
Here is the full code for your reference.
#!usr/bin/env
# import libraries
from PIL import Image
from PIL import ImageDraw
# open image
img = Image.open('/home/ubuntu/image.png')
# draw image object
I1 = ImageDraw.Draw(img)
# add text to image
I1.text((28, 36), "hello world", fill=(255, 0, 0))
# save image
img.save("/home/ubuntu/image.png")
In this article, we have learnt how to easily add text to image.
Also read:
How to Find & Copy Files in Linux
How to Rename Downloaded File Using Wget
Wget Limit Download Speed Rate
How to Backup & Restore PostgreSQL Database
How to Check Git Diff Between Commits
Sreeram has more than 10 years of experience in web development, Python, Linux, SQL and database programming.