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.
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.
Draw function of the
ImageDraw module creates an object that we can use to draw on the given image.
im: This is the image we have to draw.
mode: This is an optional mode we use for color values, such as
We can use the
text function of the
ImageDraw module to draw the given text/string at the given position on the image.
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.
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()
open()method to read the
educative.jpeginto the memory.
draw()function to create an object from the image read into memory. We can use it to draw.
txt, the text we have to write on the image.
text()function to write
txtonto the image. Here, we pass
(250,250)as the coordinates of the text and
(0, 0, 0)as the color of the text.
View all Courses