Pillow is the friendly fork of PIL (Python Imaging Library) and is an easy-to-use library for opening, manipulating, and saving many different image file formats in Python. Here’s a short tutorial on how to use it:
First, you need to install Pillow. You can do this using pip:
pip install Pillow
To open and view an image with Pillow, you can use the Image
module:
from PIL import Image # Open an image file
image = Image.open('path/to/your/image.jpg') # Display the image
image.show()
Replace 'path/to/your/image.jpg'
with the actual path to your image file.
You can resize images using the resize()
method:
# Resize the image to 300x300
resized_image = image.resize((300, 300)) # Show the resized image
resized_image.show()
To crop an image, use the crop()
method:
# Define the box to crop (left, upper, right, lower)
box = (100, 100, 400, 400)
cropped_image = image.crop(box) # Show the cropped image
cropped_image.show()
You can rotate images by a certain degree using the rotate()
method:
# Rotate the image by 90 degrees
rotated_image = image.rotate(90) # Show the rotated image
rotated_image.show()
To save an image, use the save()
method:
# Save the rotated image to a file
rotated_image.save('path/to/save/rotated_image.jpg')
Replace 'path/to/save/rotated_image.jpg'
with the desired save location and file name.
Pillow also supports applying different filters to images. Here’s how to apply a blur filter:
from PIL import ImageFilter # Apply a blur filter to the image
blurred_image = image.filter(ImageFilter.BLUR) # Show the blurred image
blurred_image.show()
Python Mega Course: Learn Python in 60 Days, Build 20 Apps
Learn Python on Udemy completely in 60 days or less by building 20 real-world applications from web development to data science.