How to use Python’s Pillow library to work with images.

Introduction to Pillow

Pillow is a popular Python library for working with images. It is a fork of the Python Imaging Library (PIL) and provides a range of functionality for manipulating and processing images in Python.

Installation

To use Pillow, you first need to install it. You can do this using pip, the Python package installer:

pip install Pillow

Opening and saving images

To open an image using Pillow, you can use the Image.open() method:

from PIL import Image

# Open an image file
image = Image.open('image.jpg')

# Display the image
image.show()

This will open an image file called image.jpg and display it using the default image viewer on your system.

To save an image, you can use the save() method:

# Save the image in a different format
image.save('image.png')

This will save the image in PNG format with the file name image.png.

Resizing images

To resize an image using Pillow, you can use the resize() method:

# Resize the image to 50% of its original size
resized_image = image.resize((int(image.width/2), int(image.height/2)))

# Display the resized image
resized_image.show()

This will create a new image that is 50% the size of the original image and display it.

Cropping images

To crop an image using Pillow, you can use the crop() method:

# Crop the image to a specific region
cropped_image = image.crop((0, 0, 100, 100))

# Display the cropped image
cropped_image.show()

This will create a new image that is cropped to the region between the top-left corner and the point (100,100), and display it.

Adding text to images

To add text to an image using Pillow, you can use the ImageDraw.Draw() method:

from PIL import ImageFont, ImageDraw

# Create a new ImageDraw object
draw = ImageDraw.Draw(image)

# Define the text to be drawn
text = 'Hello, world!'

# Define the font to use
font = ImageFont.truetype('arial.ttf', 36)

# Draw the text on the image
draw.text((50, 50), text, fill=(255, 255, 255), font=font)

# Display the modified image
image.show()

This will create a new ImageDraw object, define some text to be drawn, and draw it on the image. The text will be drawn at the point (50,50) using the specified font and fill color.

Conclusion

In this post, we covered the basics of how to use Python’s Pillow library to work with images. We looked at how to open and save images, resize and crop images, and add text to images. Pillow provides a wide range of functionality for working with images in Python, making it a powerful tool for image processing and manipulation.

Related Posts

Leave a Reply

Your email address will not be published. Required fields are marked *