DEV Community

Cover image for How to add a caption to an image using Python code?
Dmitry Romanoff
Dmitry Romanoff

Posted on

How to add a caption to an image using Python code?

Here is an example Python code using the Pillow library to add a caption to an image:

from PIL import Image, ImageDraw, ImageFont

# Open the image
image = Image.open("img_example.jpg")

# Define font and font size
font = ImageFont.truetype("Waree-Bold.ttf", 120)

# Define text
text = "Caption Example"

# Create a draw object
draw = ImageDraw.Draw(image)

# Calculate text size
text_size = draw.textsize(text, font=font)

# Calculate text position
x = image.width // 2 - text_size[0] // 2
y = image.height - 240 - text_size[1] // 2

# Draw text on image
draw.text((x, y), text, fill='white', font=font)

# Save the new image with the caption
image.save("img_example_with_caption.jpg")
Enter fullscreen mode Exit fullscreen mode

This code opens an image file named "img_example.jpg", adds the caption "Caption Example" at the bottom center of the image, and saves the new image as "img_example_with_caption.jpg".

You can customize the font, font size, text, text color, and caption position to fit your specific needs.

To get a list of fonts on your system, run the following command:

locate .ttf

Top comments (0)