Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
April 12, 2023 09:18 am GMT

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 imageimage = Image.open("img_example.jpg")# Define font and font sizefont = ImageFont.truetype("Waree-Bold.ttf", 120)# Define texttext = "Caption Example"# Create a draw objectdraw = ImageDraw.Draw(image)# Calculate text sizetext_size = draw.textsize(text, font=font)# Calculate text positionx = image.width // 2 - text_size[0] // 2y = image.height - 240 - text_size[1] // 2# Draw text on imagedraw.text((x, y), text, fill='white', font=font)# Save the new image with the captionimage.save("img_example_with_caption.jpg")

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


Original Link: https://dev.to/dm8ry/how-to-add-a-caption-to-an-image-using-python-code-2ddd

Share this article:    Share on Facebook
View Full Article

Dev To

An online community for sharing and discovering great ideas, having debates, and making friends

More About this Source Visit Dev To