Image Manipulation with Pillow
Pillow provides powerful tools to manipulate images effortlessly. This section covers essential image manipulation techniques, including resizing, cropping, rotating, flipping, and applying transformations.
Resizing Images
The resize()
method allows you to resize an image to a specific width and height.
Example: Resizing an Image
from PIL import Image
# Open an image
img = Image.open("example.jpg")
# Resize the image to 200x300 pixels
resized_img = img.resize((200, 300))
resized_img.show()
# Save the resized image
resized_img.save("resized_example.jpg")
Maintaining Aspect Ratio
To resize while maintaining the original aspect ratio, use the thumbnail()
method:
# Resize with aspect ratio
img.thumbnail((200, 200))
img.show()
Cropping Images
Use the crop()
method to extract a portion of the image.
Example: Cropping an Image
# Define the cropping area (left, upper, right, lower)
crop_area = (50, 50, 200, 200)
cropped_img = img.crop(crop_area)
cropped_img.show()
# Save the cropped image
cropped_img.save("cropped_example.jpg")
Rotating and Flipping Images
Rotating Images
The rotate()
method rotates the image by a specified angle.
# Rotate the image by 90 degrees
rotated_img = img.rotate(90)
rotated_img.show()
# Save the rotated image
rotated_img.save("rotated_example.jpg")
Flipping Images
- Horizontal Flip: Use the
Image.FLIP_LEFT_RIGHT
constant. - Vertical Flip: Use the
Image.FLIP_TOP_BOTTOM
constant.
# Flip the image horizontally
flipped_img = img.transpose(Image.FLIP_LEFT_RIGHT)
flipped_img.show()
# Flip the image vertically
flipped_img_v = img.transpose(Image.FLIP_TOP_BOTTOM)
flipped_img_v.show()
Applying Transformations
Pillow supports several transformation methods to manipulate images further.
Example: Transposing an Image
The transpose()
method applies transformations like rotations and mirroring.
# Transpose the image (e.g., 90-degree rotation)
transposed_img = img.transpose(Image.ROTATE_90)
transposed_img.show()
Try It Yourself
Problem 1: Resize and Save an Image
Write a script to resize sample.jpg
to 300x300 pixels and save it as sample_resized.jpg
.
Show Solution
from PIL import Image
img = Image.open("sample.jpg")
resized_img = img.resize((300, 300))
resized_img.save("sample_resized.jpg")
resized_img.show()
Problem 2: Crop a Face from an Image
Write a script to crop the face region from an image named group.jpg
and save it as face.jpg
.
Show Solution
img = Image.open("group.jpg")
crop_area = (100, 50, 300, 250) # Define coordinates
face_img = img.crop(crop_area)
face_img.save("face.jpg")
face_img.show()
With these techniques, you can manipulate images creatively and prepare them for further processing. Stay tuned for more advanced image handling operations in the upcoming sections!