How to Resize Image in Python: Simple Guide with Example
To resize an image in Python, use the
Pillow library's Image.resize() method. First, open the image with Image.open(), then call resize() with the new size as a tuple, and finally save or use the resized image.Syntax
The basic syntax to resize an image using Pillow is:
Image.open(path): Opens the image file.image.resize((width, height)): Resizes the image to the specified width and height.image.save(path): Saves the resized image to a file.
python
from PIL import Image image = Image.open('input.jpg') resized_image = image.resize((new_width, new_height)) resized_image.save('output.jpg')
Example
This example opens an image named input.jpg, resizes it to 200 pixels wide and 100 pixels tall, and saves it as output.jpg.
python
from PIL import Image # Open the original image image = Image.open('input.jpg') # Resize image to 200x100 pixels resized_image = image.resize((200, 100)) # Save the resized image resized_image.save('output.jpg') print('Image resized and saved as output.jpg')
Output
Image resized and saved as output.jpg
Common Pitfalls
Common mistakes when resizing images include:
- Not maintaining the aspect ratio, which can distort the image.
- Forgetting to import the
Pillowlibrary or install it first usingpip install Pillow. - Using incorrect size tuples (must be integers).
- Not saving the resized image, so changes are lost.
To keep the aspect ratio, calculate the new height based on the original width and height.
python
from PIL import Image # Wrong: distorts image by ignoring aspect ratio image = Image.open('input.jpg') resized = image.resize((300, 100)) # fixed size resized.save('wrong_output.jpg') # Right: maintain aspect ratio width_percent = (300 / float(image.size[0])) height_size = int((float(image.size[1]) * float(width_percent))) resized_correct = image.resize((300, height_size)) resized_correct.save('correct_output.jpg')
Quick Reference
Tips for resizing images in Python:
- Use
Pillowlibrary:pip install Pillow. - Open images with
Image.open(). - Resize with
resize((width, height)). - Maintain aspect ratio to avoid distortion.
- Save resized images with
save().
Key Takeaways
Use Pillow's Image.resize() method to resize images in Python.
Always maintain the aspect ratio to prevent image distortion.
Install Pillow with pip before using it.
Remember to save the resized image to keep changes.
Use integer tuples for the new size dimensions.