How to Create Thumbnail in Python Using Pillow
You can create a thumbnail in Python using the
Pillow library by opening an image and calling its thumbnail() method with the desired size. This method resizes the image while keeping its aspect ratio, making it easy to generate smaller preview images.Syntax
To create a thumbnail, you first open an image with Image.open(), then call thumbnail(size) on it. The size is a tuple like (width, height) that sets the maximum size of the thumbnail. The image is resized in place, keeping its aspect ratio.
python
from PIL import Image image = Image.open('path/to/image.jpg') image.thumbnail((128, 128)) # Resize image to max 128x128 image.save('path/to/thumbnail.jpg')
Example
This example opens an image file, creates a thumbnail with a maximum size of 100x100 pixels, and saves the thumbnail as a new file. It shows how easy it is to generate a smaller version of an image for previews.
python
from PIL import Image # Open an existing image image = Image.open('example.jpg') # Create a thumbnail with max size 100x100 image.thumbnail((100, 100)) # Save the thumbnail image.save('example_thumbnail.jpg') print('Thumbnail created successfully.')
Output
Thumbnail created successfully.
Common Pitfalls
- Not installing Pillow: You must install Pillow with
pip install Pillowbefore using it. - Using
resize()instead ofthumbnail():resize()changes the image size but does not keep the aspect ratio automatically. - Calling
thumbnail()multiple times on the same image can cause unexpected results because it modifies the image in place. - Not saving the thumbnail after creating it will not store the smaller image.
python
from PIL import Image image = Image.open('example.jpg') # Wrong: resize without aspect ratio resized = image.resize((100, 100)) # May distort image resized.save('wrong_thumbnail.jpg') # Right: use thumbnail to keep aspect ratio image = Image.open('example.jpg') image.thumbnail((100, 100)) image.save('correct_thumbnail.jpg')
Quick Reference
Here is a quick summary of the main steps and tips for creating thumbnails in Python:
| Step | Description |
|---|---|
| Install Pillow | Run pip install Pillow to add the library. |
| Open Image | Use Image.open('file.jpg') to load your image. |
| Create Thumbnail | Call image.thumbnail((width, height)) to resize. |
| Save Thumbnail | Use image.save('thumbnail.jpg') to save the result. |
| Keep Aspect Ratio | thumbnail() keeps the image proportions automatically. |
Key Takeaways
Use Pillow's
thumbnail() method to create thumbnails that keep aspect ratio.Always save the image after creating the thumbnail to store the smaller version.
Install Pillow with
pip install Pillow before running your code.Avoid using
resize() if you want to keep the image proportions.The
thumbnail() method modifies the image in place, so reopen if needed.