”;
Adding text to images is a common image processing task that involves overlaying text onto an image. This can be done for various purposes such as adding captions, labels, watermarks or annotations to images. When adding text to images we can typically specify the text content, font, size, color and position.
In Pillow (PIL) We can use the text() method from the ImageDraw module to add text to an image.
The text() method
The text() method allows us to specify the position, text content, font and color of the text we want to add.
Syntax
The below is the basic syntax and parameters for using the text() method −
PIL.ImageDraw.Draw.text(xy, text, fill=None, font=None, anchor=None, spacing=0, align="left")
-
xy − The position where the text should be placed. It should be a tuple ”(x, y)” representing the coordinates.
-
text − The text content that we want to add to the image.
-
fill (optional) − The color of the text. It can be specified as a tuple ”(R, G, B)” for RGB colors a single integer for grayscale colors or as a named color.
-
font (optional) − The font to use for the text. We can specify the font using ”ImageFont.truetype()” or ”ImageFont.load()”.
-
anchor (optional) − Specifies how the text should be anchored. Options include “left”, “center”, “right”, “top”, “middle” and “bottom”.
-
spacing (optional) − Specifies the spacing between lines of text. Use positive values to increase spacing or negative values to reduce spacing.
-
align (optional) − Specifies the horizontal alignment of the text within the bounding box. Options include “left”, “center” and “right”.
Following is the input image used in all the examples of this chapter.
Example
In this example we are adding the text Tutorialspointto the input image using the text() method of the Image module.
from PIL import Image, ImageDraw, ImageFont #Open an image image = Image.open("Images/book.jpg") #Create a drawing object draw = ImageDraw.Draw(image) #Define text attributes text = "Tutorialspoint" font = ImageFont.truetype("arial.ttf", size=30) text_color = (255, 0, 0) #Red position = (50, 50) #Add text to the image draw.text(position, text, fill=text_color, font=font) #Save or display the image with the added text image.save("output Image/textoutput.jpg") opentext = Image.open("output Image/textoutput.jpg") opentext.show()
Output
Example
Here this is another example of adding text to the image by using the text() method of the ImageDraw module.
from PIL import Image, ImageDraw, ImageFont #Open an image image = Image.open("Images/book.jpg") #Create a drawing object draw = ImageDraw.Draw(image) #Define text attributes text = "Have a Happy learning" font = ImageFont.truetype("arial.ttf", size=10) text_color = (255, 0, 255) position = (150, 100) #Add text to the image draw.text(position, text, fill=text_color, font=font) #Save or display the image with the added text image.save("output Image/textoutput.jpg") opentext = Image.open("output Image/textoutput.jpg") opentext.show()
Output
”;