How to add text on an image using pillow in Python?

How to add text on an image using pillow in Python?

Adding text to an image using the Pillow library in Python is a straightforward process. Pillow is an updated fork of the PIL (Python Imaging Library) and provides a wide range of capabilities for image processing. Here's a step-by-step guide to adding text to an image using Pillow:

Step 1: Install Pillow

If you haven't installed Pillow yet, you can do so using pip:

pip install pillow 

Step 2: Load the Image

First, you need to load the image you want to add text to:

from PIL import Image image_path = 'path_to_your_image.jpg' # Replace with your image path image = Image.open(image_path) 

Step 3: Prepare the Draw Object

Pillow uses a Draw object to modify images. You also need to define the font and size of the text:

from PIL import ImageDraw, ImageFont draw = ImageDraw.Draw(image) # Define font (standard built-in font or any .ttf file) font_path = 'path_to_your_font.ttf' # Replace with your font path font_size = 36 font = ImageFont.truetype(font_path, font_size) 

If you don't have a specific font file, you can use a default font provided by Pillow:

font = ImageFont.load_default() 

Step 4: Add Text to the Image

Now, you can add text to the image. You need to specify the position where you want the text to appear and the color of the text:

text = "Your text here" position = (100, 100) # Change to desired position text_color = (255, 255, 255) # RGB color, this is white draw.text(position, text, fill=text_color, font=font) 

Step 5: Save or Display the Image

Finally, you can either save the image or display it:

# Save the edited image output_path = 'output_image.jpg' # Replace with your desired output path image.save(output_path) # Or display the image (in notebooks or if PIL.Image.show() works in your environment) image.show() 

Complete Example

Here's the complete program assembled together:

from PIL import Image, ImageDraw, ImageFont # Load the image image_path = 'path_to_your_image.jpg' image = Image.open(image_path) # Prepare draw object and font draw = ImageDraw.Draw(image) font_path = 'path_to_your_font.ttf' font_size = 36 font = ImageFont.truetype(font_path, font_size) # font = ImageFont.load_default() # Use default font # Add text text = "Your text here" position = (100, 100) text_color = (255, 255, 255) draw.text(position, text, fill=text_color, font=font) # Save or display the image output_path = 'output_image.jpg' image.save(output_path) # image.show() 

Remember to replace path_to_your_image.jpg, path_to_your_font.ttf, and output_image.jpg with your actual file paths and names. The position, font size, and text color can also be adjusted according to your preference.


More Tags

json-schema-validator multi-level enums mongodb-atlas themes location-services checkbox solidity ngfor orbital-mechanics

More Programming Guides

Other Guides

More Programming Examples