Image Resizer Tool using Pillow Library
IntermediateResize and compress images with Python's Pillow library
1) Project Overview
The Image Resizer Tool is a desktop Python program that allows users to quickly resize image files (e.g., .jpg, .png) to custom dimensions or by a percentage.
It's useful for:
- Compressing images for websites or apps
- Standardizing photo sizes
- Reducing storage space
With this project, students will create a simple command-line image utility that takes input from the user and processes images using Python's Pillow (PIL) library.
2) Learning Objectives
By completing this project, learners will:
- β Understand how to use the Pillow library for image processing
- β Learn to open, resize, and save image files programmatically
- β Practice file handling and path management using os module
- β Learn error handling for user input and missing files
- β Strengthen logic for real-world automation tasks
3) Step-by-Step Explanation
Follow these steps to build the image resizer:
- Install Pillow β First, install the Pillow library (if not already installed):
pip install Pillow - Import Required Modules β We'll use PIL (from Pillow) to manipulate images and os to check file paths
- Load an Image β Ask the user for the path of an image file, then open it using Image.open()
- Choose Resize Option β Allow the user to resize by specific width and height, or resize by percentage (e.g., 50% smaller)
- Save the Resized Image β After resizing, save the new image to disk, appending _resized to the filename
- Handle Errors β Use try-except blocks to handle file not found errors and invalid inputs
4) Complete Verified Python Code
You can copy this into a file named image_resizer.py and run it.
# -----------------------------
# πΌοΈ Image Resizer Tool
# -----------------------------
# Author: Your Name
# Level: Intermediate
# Requires: Pillow (pip install Pillow)
from PIL import Image
import os
def resize_image(image_path, output_path, width=None, height=None, scale_percent=None):
"""Resize image by given width/height or percentage."""
try:
# Open the image
img = Image.open(image_path)
original_width, original_height = img.size
print(f"Original size: {original_width}x{original_height}")
# Resize by scale percent
if scale_percent:
new_width = int(original_width * scale_percent / 100)
new_height = int(original_height * scale_percent / 100)
else:
# Resize by width and height
new_width = width
new_height = height
# Resize the image
resized_img = img.resize((new_width, new_height))
resized_img.save(output_path)
print(f"β
Image resized and saved successfully at: {output_path}")
except FileNotFoundError:
print("β Error: Image file not found. Please check the path.")
except Exception as e:
print(f"β Unexpected error: {e}")
def main():
print("===== πΌοΈ IMAGE RESIZER TOOL =====")
image_path = input("Enter the path of the image: ").strip()
if not os.path.exists(image_path):
print("β The specified image file does not exist.")
return
choice = input("Resize by (1) Width & Height or (2) Percentage? Enter 1 or 2: ")
if choice == "1":
width = int(input("Enter new width (pixels): "))
height = int(input("Enter new height (pixels): "))
output_path = os.path.splitext(image_path)[0] + "_resized.jpg"
resize_image(image_path, output_path, width, height)
elif choice == "2":
percent = int(input("Enter resize percentage (e.g., 50 for 50%): "))
output_path = os.path.splitext(image_path)[0] + f"_{percent}percent.jpg"
resize_image(image_path, output_path, scale_percent=percent)
else:
print("β Invalid choice. Please restart and choose either 1 or 2.")
if __name__ == "__main__":
main()
β No syntax or runtime errors when tested in Python 3.8+.
5) Output Example
Sample Run:
Enter the path of the image: C:\Users\Tajammul\Pictures\sunset.jpg
Resize by (1) Width & Height or (2) Percentage? Enter 1 or 2: 2
Enter resize percentage (e.g., 50 for 50%): 50
Original size: 1920x1080
β Image resized and saved successfully at: C:\Users\Tajammul\Pictures\sunset_50percent.jpg
6) Extension Challenge
π― Advanced Version Idea
Goal: Transform the tool into a user-friendly desktop application:
- Add a GUI Interface using Tkinter to select images through a file dialog (tkinter.filedialog)
- Show a preview of the original and resized image
- Add a progress bar
This would transform the tool into a user-friendly desktop application.
7) Summary
This project demonstrates how Python can perform real-world automation tasks such as image processing using simple logic and powerful libraries like Pillow.
Learners gain:
- Confidence in handling files and images
- Understanding of the Pillow library
- A ready-to-use tool they can improve upon
π‘ "With just a few lines of Python, you can create tools that save time and improve productivity β that's the real power of coding!"