Back to Python
2026-04-226 min read

Image Text (Python Programming)

Learn Image Text (Python Programming) step by step with clear examples and exercises.

Why This Matters

In web development and data visualization, combining images with text is a common requirement. Python, with its extensive libraries like PIL (Python Imaging Library) and matplotlib, offers powerful solutions for handling image-text tasks. Understanding how to manipulate images with text can help you create engaging websites, data visualizations, and even AI applications.

Why This Matters

In the realm of web development and data visualization, integrating images and text is a frequent necessity. Python, equipped with robust libraries such as PIL (Python Imaging Library) and matplotlib, provides potent solutions for handling image-text tasks. Mastering the art of manipulating images with text can empower you to craft captivating websites, data visualizations, and even AI applications.

Prerequisites

Before delving into the core concept, ensure you have a solid understanding of Python basics, including variables, functions, and control structures. Familiarity with Python libraries like PIL (Python Imaging Library) will be beneficial but not mandatory as we'll cover the essentials in this lesson.

Core Concept

To position text over an image in Python, we can use the PIL library. First, install it using pip:

pip install pillow

Now let's create a simple example where we place some text on top of an image.

from PIL import Image, ImageDraw, ImageFont

Open the image file

image = Image.open('background.jpg')

Prepare the drawing context

draw = ImageDraw.Draw(image)

Define the font and text color

font = ImageFont.truetype('arial.ttf', 30)

text_color = (255, 255, 255)

Add the text to the image at a specific position

draw.text((100, 100), "Hello, World!", font=font, fill=text_color)

Save and display the output

image.save('output.jpg')

image.show()


In this example, we open an image, create a drawing context, define the text color and font, add the text to the image at a specific position, save the modified image, and finally display it.

Core Concept (Expanded)

The Python Imaging Library (PIL) is a powerful tool for handling various image processing tasks, including adding text to images. To get started, make sure you have PIL installed:

pip install pillow

Now let's create a simple example where we place some text on top of an image.

from PIL import Image, ImageDraw, ImageFont

Open the image file

image = Image.open('background.jpg')

Prepare the drawing context

draw = ImageDraw.Draw(image)

Define the font and text color

font = ImageFont.truetype('arial.ttf', 30)

text_color = (255, 255, 255)

Add the text to the image at a specific position

draw.text((100, 100), "Hello, World!", font=font, fill=text_color)

Save and display the output

image.save('output.jpg')

image.show()


In this example, we open an image, create a drawing context, define the text color and font, add the text to the image at a specific position, save the modified image, and finally display it. By manipulating images with text, you can create engaging websites, data visualizations, and even AI applications.

Worked Example

Let's extend our previous example by adding more text and adjusting the positions for better readability.

from PIL import Image, ImageDraw, ImageFont

Open the image file

image = Image.open('background.jpg')

Prepare the drawing context

draw = ImageDraw.Draw(image)

Define the font and text colors

font = ImageFont.truetype('arial.ttf', 20)

text_colors = [(255, 69, 0), (0, 128, 64), (75, 0, 130)]

Add the text to the image at different positions

for i in range(len(text_colors)):

draw.text((100 + i 200, 100 + i 80), f"Text {i+1}", font=font, fill=text_colors[i])

Save and display the output

image.save('output.jpg')

image.show()


In this example, we loop through the text colors and positions, adding each text at a different location on the image. By adjusting the positions of the text, you can ensure better readability and improve the overall appearance of your images.

Common Mistakes

  • Forgetting to open the image file: Always use Image.open() to load the image before working with it.
  • Not defining the font or text color: Make sure you have appropriate font and text colors set before adding text to the image.
  • Incorrect positioning of the text: Adjust the x and y coordinates of the draw.text() function to place the text at the desired location on the image.
  • Not saving or displaying the output: After modifying the image, don't forget to save and display it using image.save('output.jpg') and image.show().
  • Using an unsupported font file: Ensure that the font file you are using is compatible with Python and PIL by checking its format (e.g., .ttf, .otf).

Common Mistakes

  • Forgetting to open the image file
  • Always use Image.open() to load the image before working with it.
  • Not defining the font or text color
  • Make sure you have appropriate font and text colors set before adding text to the image.
  • Incorrect positioning of the text
  • Adjust the x and y coordinates of the draw.text() function to place the text at the desired location on the image.
  • Not saving or displaying the output
  • After modifying the image, don't forget to save and display it using image.save('output.jpg') and image.show().
  • Using an unsupported font file
  • Ensure that the font file you are using is compatible with Python and PIL by checking its format (e.g., .ttf, .otf).

Practice Questions

  1. Create an image with two text boxes side by side.
  2. Add a watermark (text or logo) to multiple images in a folder.
  3. Create a bar chart on top of an image using matplotlib.
  4. Write a function that takes an image and a list of texts, positions, and colors as input and returns the modified image with the specified text.
  5. Add a drop shadow effect to the text on the image.
  6. Create a script that resizes multiple images in a folder while maintaining their aspect ratio.
  7. Write a function that rotates an image by a specified angle.
  8. Combine multiple images into a single collage using PIL.
  9. Add a border around the text on the image to make it stand out more.
  10. Create a script that automatically generates a thumbnail for each video in a folder.

FAQ

Q: How can I change the font size in my text?

A: You can change the font size by adjusting the second argument of ImageFont.truetype(). For example, ImageFont.truetype('arial.ttf', 40) will set the font size to 40 pixels.

Q: How do I center text on an image?

A: To center text horizontally and vertically, calculate the midpoint of the image and use it as the x and y coordinates for draw.text(). For example, image_width = image.width; image_height = image.height; draw.text((image_width / 2, image_height / 2), "Centered Text", font=font, fill=text_color)

Q: How do I add a drop shadow effect to the text on an image?

A: To create a drop shadow effect, you can duplicate the original image and offset the text slightly for each copy. Then, combine all the copies using the Image.alpha_composite() method. Here's a simple example:

from PIL import Image, ImageDraw, ImageFont
import math

... (previous code)

Define the drop shadow parameters

shadow_offset = (5, 5)

shadow_color = (0, 0, 0, 128)

Create a copy of the image and offset the text for the shadow

shadow_image = image.copy()

draw.text((shadow_offset[0], shadow_offset[1]), "Text", font=font, fill=shadow_color)

Combine the original and shadow images with alpha compositing

result = Image.alpha_composite(image, shadow_image)

result.save('output.jpg')

result.show()

Image Text (Python Programming) | Python | XQA Learn