English 中文(简体)
Python Pillow - Writing Text on Image
  • 时间:2024-11-03

Python Pillow - Writing Text on Image


Previous Page Next Page  

You can write text on images by passing the location of the text, the text itself and the color of the text. We can pass multiple other parameters to this method.

Example

from PIL import Image, ImageDraw

img = Image.open(beach1.jpg )
d1 = ImageDraw.Draw(img)
d1.text((28, 36), "Hello, TutorialsPoint!", fill=(255, 0, 0))
img.show()
img.save("images/image_text.jpg")

Input

Tutorials Point

Output

If you save the above program as Example.py and execute, it will add the given text on it, and displays it using the standard PNG display utipty, as follows −

Tutorials Point1

Selecting the font

There are numerous ways to select the font used for writing on the image. We can either load fonts directly from the system by passing the full path to the function, or we can use the ImageFont to load a TrueType font.

Example

from PIL import Image, ImageDraw, ImageFont

img = Image.open( images/logo.jpg )
d1 = ImageDraw.Draw(img)
myFont = ImageFont.truetype( E:/PythonPillow/Fonts/FreeMono.ttf , 40)
d1.text((0, 0), "Sample text", font=myFont, fill =(255, 0, 0))
img.show()
img.save("images/image_text.jpg")

Output

Tutorials Point2 Advertisements