⚡ Python Power Shots — 🖼️ Image Compressor/Resizer using Pillow
Posted on: December 15, 2025
Description:
📌 Introduction
Large images can slow down websites, eat up storage, and make sharing difficult.
With Python’s Pillow library, you can quickly compress or resize images while keeping them visually clean.
This Power Shot shows how to reduce file size, resize images proportionally, and save optimized versions — all with just a few lines of Python.
🔎 Explanation
- Image.open() loads the image for processing.
- Resizing is done by calculating the width ratio and adjusting the height automatically to maintain aspect ratio.
- Compression works by reducing the output quality (quality=40 etc.).
- optimize=True helps Pillow reduce unnecessary metadata.
- The script outputs a smaller, faster, web-friendly version of the original image.
You can use this for:
- Preparing assets for your website
- Compressing photos before posting online
- Reducing file sizes in automation workflows
- Creating thumbnails
✅ Key Takeaways
- 🖼️ Easily compress or resize images using Pillow.
- 📦 Great for storage optimization and web performance.
- ⚙️ Fully customizable: set quality, resolution, and output names.
Code Snippet:
# Import Image from Pillow for image processing
from PIL import Image
import os
# --- Step 1: Configure input/output paths ---
INPUT_IMAGE = "input.jpg" # Replace with your file
OUTPUT_IMAGE = "compressed.jpg" # Output filename
# --- Step 2: Choose compression settings ---
QUALITY = 40 # Quality level (1–95), lower = smaller size
MAX_WIDTH = 800 # Resize width (keeps aspect ratio)
RESIZE = True # Set to False to skip resizing
# --- Step 3: Open the image ---
if not os.path.exists(INPUT_IMAGE):
raise FileNotFoundError(f"Input image not found: {INPUT_IMAGE}")
img = Image.open(INPUT_IMAGE)
# --- Step 4: Resize while maintaining aspect ratio ---
if RESIZE:
w_percent = MAX_WIDTH / float(img.size[0])
new_height = int(float(img.size[1]) * w_percent)
img = img.resize((MAX_WIDTH, new_height), Image.LANCZOS)
print(f"📐 Resized to: {MAX_WIDTH} x {new_height}px")
# --- Step 5: Save compressed image ---
img.save(
OUTPUT_IMAGE,
optimize=True,
quality=QUALITY
)
print(f"✅ Image compressed and saved as '{OUTPUT_IMAGE}'")
Link copied!
Comments
Add Your Comment
Comment Added!
No comments yet. Be the first to comment!