1. Loading and Saving Images
To load images in Pillow, you use the Image class. Once loaded, the image can be transformed and saved in various formats. Let's go through the basic operations for loading and saving images.
Loading an Image
To load an image, use the method Image.open(). It lets you open images in any supported format.
from PIL import Image
# Opening an image
image = Image.open("example.jpg")
# Printing file info
print(image.format) # Image format, like JPEG or PNG
print(image.size) # Dimensions of the image (width, height)
print(image.mode) # Color mode, like RGB or Grayscale
This code loads the image example.jpg and prints its main characteristics: format, size, and color mode. If the image is not in the same folder, specify the full file path.
Saving an Image
After loading and modifying an image, you can save it in any supported format by simply specifying the desired file extension in the file name. The save() method lets you set the output file name and format.
# Saving an image in another format
image.save("example.png") # Saves the image in PNG format
You can also adjust the quality of the saved image to reduce file size, which is especially useful for JPEG images.
# Saving with adjusted quality
image.save("compressed_example.jpg", quality=85) # The quality value ranges from 1 to 95
2. Resizing Images
Resizing is one of the most common tasks when working with images. Pillow offers several ways to resize, including setting specific width and height parameters, proportional resizing, and creating thumbnails.
Resizing with the resize() Method
The resize() method lets you specify the exact dimensions of an image (width and height), but the image may get distorted if the new dimensions don't maintain its original aspect ratio.
# Setting a new size
new_size = (800, 600)
resized_image = image.resize(new_size)
# Saving the resized image
resized_image.save("resized_example.jpg")
In this example, the image is resized to 800x600 pixels and saved as a new file. If the original image has a different aspect ratio, it will be stretched or squeezed to fit the new dimensions.
Proportional Resizing with thumbnail()
To resize an image while maintaining its aspect ratio, use the thumbnail() method. This method automatically reduces the image so that it fits within the specified dimensions, keeping the original aspect ratio. This is especially handy for creating image thumbnails.
# Creating a thumbnail with max dimensions of 400x400 pixels
image.thumbnail((400, 400))
# Saving the thumbnail
image.save("thumbnail_example.jpg")
The thumbnail() method modifies the image "in place," meaning the changes occur on the original image object. Once thumbnail() is applied, Pillow resizes the image so that its dimensions don't exceed 400x400 pixels while maintaining the aspect ratio.
Scaling with Aspect Ratio Using ImageOps.fit()
Sometimes, you need to resize an image to exactly match specific dimensions while keeping the aspect ratio, cropping excess parts. For such cases, you can use the ImageOps.fit() method.
from PIL import ImageOps
# Setting a target size
target_size = (400, 400)
fitted_image = ImageOps.fit(image, target_size, method=Image.LANCZOS)
# Saving the cropped image
fitted_image.save("fitted_example.jpg")
The ImageOps.fit() method automatically crops the image to fit specified dimensions without distortion. For example, if the original image is rectangular, the method will crop the edges to make it square and fit 400x400 pixels.
3. Full Code Example
Below is an example code that combines all the methods we covered — from loading to resizing and saving images.
from PIL import Image, ImageOps
# Opening an image
image = Image.open("example.jpg")
# Resizing without keeping the aspect ratio
resized_image = image.resize((800, 600))
resized_image.save("resized_example.jpg")
# Proportional resizing
image.thumbnail((400, 400))
image.save("thumbnail_example.jpg")
# Scaling with cropping to fit target size
fitted_image = ImageOps.fit(image, (400, 400), method=Image.LANCZOS)
fitted_image.save("fitted_example.jpg")
Explanations of Resizing Methods
-
resize(): Lets you specify arbitrary dimensions, but it may distort the image if the new dimensions differ from the original aspect ratio. -
thumbnail(): Resizes the image while maintaining its aspect ratio. Useful for creating thumbnails and reducing large images. -
ImageOps.fit(): Scales the image to specified dimensions while cropping edges. Used when it's important to fit exact dimensions without distortion.
4. Tips:
Practical Applications of Image Resizing
- Optimizing images for websites: Large images can slow down page loading, so it's essential to optimize them by reducing size without losing quality.
- Creating thumbnails for galleries: Using
thumbnail()allows you to quickly create image thumbnails for previewing. - Fitting images to specific dimensions: When you need an image to fit fixed dimensions, like for avatars or profiles, the
ImageOps.fit()method allows cropping and scaling to match these requirements.
Method Selection Tips
Use resize() when you need to set exact width and height dimensions, and don't mind if the aspect ratio changes.
Use thumbnail() to create thumbnails or when you want to shrink an image while maintaining its proportions.
Use ImageOps.fit() when you need an image of specific dimensions but without distorting proportions. This method crops excess parts, making it perfect for fitting images into specific frames.
GO TO FULL VERSION