Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

python

How to write text on an image in Python

Ravi

Overview

We can write text on an image in Python using the ImageDraw module of the Python Imaging Library (PIL).

This library supports a wide range of file formats. It is designed for an efficient internal representation of image data, and provides powerful image processing capabilities.

The ImageDraw module

For images, the ImageDraw module provides a simple 2D graphics operations. We can use this module to produce new photographs, annotate or edit old photographs, and generate graphics.

The Draw function

The Draw function of the ImageDraw module creates an object that we can use to draw on the given image.

Syntax

PIL.ImageDraw.Draw(im, mode=None)

Parameters

  • im: This is the image we have to draw.
  • mode: This is an optional mode we use for color values, such as RGB or RGBA.

The text function

We can use the text function of the ImageDraw module to draw the given text/string at the given position on the image.

Syntax

ImageDraw.text(xy, text, fill=None, font=None, anchor=None, spacing=4, align='left', direction=None, features=None, language=None, stroke_width=0, stroke_fill=None, embedded_color=False)

Some important and frequently used parameters of the function are as follows:

  • xy: These are the coordinates of the text to write.
  • text: This is the text/string to be drawn.
  • fill: This is the color we use for the text.
  • font: This is the font we use for the text.
  • anchor: This is the text anchor alignment.
  • spacing: Ths is the number of pixels between lines if there are newline characters in the given text.
  • align: This is the relative alignment of lines for multi-line texts.
  • direction: This is the direction of the text.
  • stroke_width: This is the width of the text stroke.
  • stroke_fill: This is the color we use for the text stroke.

Example

from PIL import Image, ImageDraw
img = Image.open("/code/educative.jpeg")
draw = ImageDraw.Draw(img)

txt = "Best platform"
draw.text((250, 250), txt, fill =(0, 0, 0))
img.save('output/graph.png')
img.show()

Explanation

  • Line 2: We use the open() method to read the educative.jpeg into the memory.
  • Line 3: We use the draw() function to create an object from the image read into memory. We can use it to draw.
  • Line 5: We define txt, the text we have to write on the image.
  • Line 6: We use the text() function to write txt onto the image. Here, we pass (250,250) as the coordinates of the text and (0, 0, 0) as the color of the text.
  • Line 7: We save the modified image to a new image file, graph.png.

RELATED TAGS

python
RELATED COURSES

View all Courses

Keep Exploring