Image Compressor using Python [Download Complete Solution]

As a Python developer, I often work with screenshots, product images, blog images, and photographs that need to be uploaded to websites or shared online. Large image files can slow down websites, consume storage, and make file sharing inconvenient.

To solve this problem, I built an Image Compressor using Python and Streamlit.

This tool allows users to upload multiple images, choose a compression quality and compression mode, compress up to 50 images in one operation, and download all compressed images in a single ZIP file.

The tool supports JPG, JPEG, PNG, and WEBP formats and includes important validations for file size, image format, corrupted files, dimensions, and duplicate filenames.

Image Compressor using Python

I developed this Image Compressor using Python and Streamlit to provide a simple interface for compressing images without manually processing each image one by one.

The application allows users to:

  • Upload multiple images simultaneously
  • Compress up to 50 images in one operation
  • Select a compression quality
  • Choose a compression mode
  • Validate images before processing
  • Handle invalid or corrupted files
  • Preserve PNG transparency where supported
  • Handle image orientation correctly
  • Display overall compression statistics
  • Download all compressed images as a ZIP file
  • Clear selected images and start again

This makes the tool useful for developers, bloggers, designers, content creators, and anyone who regularly works with large image files.

If you are interested in working with Python graphical interfaces, you can also explore our guide on Python GUI Programming. For working with images in Python applications, you may also find How to Save Images to a File in Python useful.

Image Compressor Python

Libraries Used in the Image Compressor

The Image Compressor uses a few important Python libraries.

import streamlit as st
import zipfile

from io import BytesIO

from PIL import Image

Streamlit

Streamlit is used to create the complete user interface.

It handles:

  • Image uploads
  • Compression settings
  • Buttons
  • Progress indicators
  • Error messages
  • Compression statistics
  • ZIP downloads

Streamlit is particularly useful when you want to turn a Python script into an interactive tool without building a complete frontend from scratch.

Pillow (PIL)

The Pillow library is responsible for image processing.

It is used to:

  • Open uploaded images
  • Detect the actual image format
  • Check image dimensions
  • Verify image integrity
  • Convert image modes when required
  • Compress images
  • Preserve transparency for supported PNG images

Pillow acts as the main image-processing engine of the application.

BytesIO

BytesIO allows the application to process images directly in memory.

Instead of saving every uploaded and compressed image temporarily to the computer, the tool works with image data in memory.

This approach is useful when generating downloadable files dynamically.

zipfile

The built-in zipfile module creates a ZIP archive containing all successfully compressed images.

This is particularly useful when users upload many files. Instead of downloading images individually, they can download everything at once.

You can also explore How to Split a File into Multiple Files in Python when working with large files and file-processing applications.

User Controls in the Image Compressor

The application includes simple controls so users can compress images without needing technical knowledge.

Upload Images

Users can upload one or multiple images.

The supported formats are:

  • JPG
  • JPEG
  • PNG
  • WEBP

The tool supports a maximum of 50 images in one batch. This limit helps maintain stable performance and prevents excessive memory usage.

The application can also display the number of selected images so users know how many files are ready for processing.

For other file-related Python operations, you can check How to Open a File in Python and How to Check if a File Exists in Python.

Compression Quality

The Compression Quality setting allows users to control the balance between image quality and file size.

For example:

Higher Quality
      ↓
Better Image Appearance
      ↓
Larger File Size

Whereas:

Lower Quality
      ↓
Smaller File Size
      ↓
More Compression

A user might choose:

  • 90–100 for better visual quality
  • 60–80 for balanced results
  • 20–50 when reducing file size is the primary goal

The actual output size depends on several factors, including:

  • Original image size
  • Image dimensions
  • Image format
  • Image content
  • Compression mode

If you need to calculate or display uploaded file sizes in your own Python projects, see How to Get File Size in MB Using Python.

Compression Mode

The tool provides three compression modes.

High Quality

This mode focuses on preserving image quality.

It is useful for:

  • Professional photographs
  • Product images
  • Portfolio images
  • Images where visual quality is important

The output file may be larger than other compression modes.

Balanced

Balanced mode provides a compromise between image quality and file size.

It is useful for:

  • Website images
  • Blog images
  • General-purpose images
  • Documentation screenshots

For most users, this is a practical default option.

Maximum Compression

This mode focuses on reducing the image file size as much as possible.

It is useful for:

  • Large batches of images
  • Storage optimization
  • Images used on lightweight web pages
  • Situations where smaller files are more important than perfect visual quality

The output may have more visible compression artifacts depending on the image.

Batch Image Compression using Python

One of the main features of this application is batch image compression.

Instead of uploading and compressing one image at a time, users can select multiple files and process them together.

For example:

Image 1
Image 2
Image 3
Image 4
...
Image 50
Image Compressor in Python

The tool processes all valid images in the selected batch. During processing, the application displays progress information so users know that compression is running.

For example:

Compressing 12 of 50

This is particularly useful when users upload larger batches.

Python lists are useful for managing multiple uploaded files. You can also read How to Find the Length of a List in Python to understand how to work with collections of files.

Validations Used in the Image Compressor

The application includes several validations to prevent errors and improve reliability.

Maximum Number of Images

The tool accepts up to:

50 images

If a user selects more than the allowed number, the application prevents processing and displays an appropriate message.

This helps control memory usage and keeps the tool responsive.

File Size Validation

Each uploaded image is checked against the configured maximum file size.

For example:

Maximum 50 MB per file

If an image exceeds the limit, it is marked as invalid. This prevents extremely large files from affecting application performance.

Actual Image Format Validation

The file extension alone is not trusted.

For example, someone could rename:

document.pdf

to:

image.jpg

The tool checks the actual image data using Pillow.

Only supported formats are accepted:

JPEG
PNG
WEBP

This provides more reliable validation than checking only the filename extension.

Corrupted Image Validation

An uploaded file may have a valid extension but still contain damaged or incomplete image data.

The application verifies the image before compression. If the image is corrupted, processing is skipped, and the user receives a clear message.

For example:

❌  abc.png — The file is not a valid image.
Image Compressor using Python

Using proper exception handling is important when processing uploaded files because a single invalid file should not necessarily crash the entire application.

Image Dimension Validation

Very large image dimensions can consume significant memory during processing. The tool checks the width and height of each uploaded image.

For example:

Maximum Width: 20000 pixels
Maximum Height: 20000 pixels

Images exceeding the configured dimensions can be rejected before compression.

Duplicate Filename Handling

Duplicate filenames can create problems when generating a ZIP file.

For example:

photo.jpg
photo.jpg

The application handles duplicate filenames to avoid files accidentally overwriting each other inside the ZIP archive. Unique filenames can be generated when required.

If you work with filenames in other Python projects, How to Get a File Name Without Extension in Python is also helpful.

Handling Invalid Files

A user may upload a combination of valid and invalid files.

For example:

image1.jpg       ✅ Valid
image2.png       ✅ Valid
file.gif         ❌ Unsupported
broken.jpg       ❌ Corrupted

The tool handles this situation intelligently. Valid images continue to be processed. Invalid files are reported separately.

For example:

⚠️ 2 files could not be processed.

View invalid files
Python Image Compressor

The user can expand the section to see the reason for each invalid file. This avoids stopping the entire batch because of one invalid image.

If all uploaded files are invalid, the application stops processing and informs the user that no valid images were found.

PNG Transparency Preservation

PNG files may contain transparent backgrounds.

For example:

  • Logos
  • Icons
  • UI graphics
  • Product images

The tool handles PNG image modes carefully so that transparency is not unnecessarily lost during processing.

This is important because converting an RGBA PNG incorrectly can result in a black or white background replacing transparency.

For developers who work extensively with images, you can also explore How to Remove Background from an Image in Python.

EXIF Orientation Handling

Photos taken with mobile phones may use EXIF metadata to store orientation information.

For example, a phone photo may appear correctly as portrait on the device but contain pixel data that requires orientation metadata.

The Image Compressor should preserve the correct visual orientation during processing.

This helps prevent compressed images from appearing:

  • Sideways
  • Upside down
  • Incorrectly rotated

This is especially important when processing images uploaded directly from smartphones.

Compression Statistics

After compression, the application calculates the overall results.

The summary includes:

  • Number of images processed
  • Total original size
  • Total compressed size
  • Total space saved

For example:

Images Processed: 2

Original Size: 0.02 MB

Compressed Size: 0.02 MB

Total Saved: 23.2%
Image Compressor

This allows users to immediately understand the effectiveness of the compression process.

Download All Compressed Images as ZIP

After successful compression, all output images are collected into a ZIP file.

Users can then click:

📦 Download All Compressed Images

The ZIP file contains all successfully compressed images.

For example:

compressed_images.zip

├── photo_1_compressed.jpg
├── photo_2_compressed.jpg
├── logo_compressed.png
├── banner_compressed.webp
└── screenshot_compressed.png

This provides a cleaner experience than displaying 50 separate download buttons.

If you want to learn more about handling directories and multiple files, read How to List Files in a Directory with Python.

Clear Selected Images

The application also provides a Clear All Selected Images option.

This allows users to:

  • Remove the current selection
  • Start a new batch
  • Avoid refreshing the entire application manually

This is particularly useful when testing different batches of images.

How the Image Compressor Works

The complete workflow is straightforward:

Upload Images
      ↓
Check Number of Images
      ↓
Validate File Size
      ↓
Validate Actual Image Format
      ↓
Check Image Integrity
      ↓
Validate Dimensions
      ↓
Process Valid Images
      ↓
Apply Compression Quality
      ↓
Apply Compression Mode
      ↓
Generate Compression Statistics
      ↓
Create ZIP File
      ↓
Download Compressed Images

This validation-first approach prevents unnecessary compression errors and improves the overall reliability of the application.

Why Use an Image Compressor Built with Python?

Building an image compressor with Python provides several advantages:

  • Full control over the compression logic
  • Custom validation rules
  • Batch processing
  • Adjustable quality settings
  • Multiple compression modes
  • Easy customization
  • Can be extended with additional features

For developers who want to build practical applications, this project is also a good example of combining Python image processing with an interactive interface.

If you are exploring Python applications, you can also learn from projects such as Creating a QR Code Generator Using Python and Making a Calculator in Python.

Frequently Asked Questions

How do I compress an image using Python?

You can use an image-processing library such as Pillow to open an image and save it again using compression settings. The output quality and format determine how much the file size changes.

Can I compress multiple images at once using Python?

Yes. You can store multiple uploaded files in a list and process them inside a loop. A batch-processing approach is useful when compressing dozens of images in one operation.

Which image formats can this Image Compressor support?

This tool supports JPG, JPEG, PNG, and WEBP images. The application also validates the actual image data instead of trusting only the filename extension.

Does image compression reduce image quality?

Lossy compression can reduce image quality, especially at lower quality settings. Higher quality settings generally preserve more detail but create larger files.

Why should I validate images before compression?

Validation prevents corrupted, unsupported, oversized, or extremely large images from causing unnecessary errors. It also provides users with clear information about files that could not be processed.

Can I download all compressed images together?

Yes. Successfully compressed images can be added to a ZIP archive. Users can then download all output files using one download button.

An Image Compressor using Python provides a practical way to reduce image file sizes while supporting batch processing, validations, compression controls, and ZIP downloads. Start with reliable image validation and compression logic, then expand the application with additional features as your requirements grow.

I hope you found this article helpful and that it gives you a clear starting point for building and customizing your own Python Image Compressor.

You May Also Like

51 Python Programs

51 PYTHON PROGRAMS PDF FREE

Download a FREE PDF (112 Pages) Containing 51 Useful Python Programs.

pyython developer roadmap

Aspiring to be a Python developer?

Download a FREE PDF on how to become a Python developer.

Let’s be friends

Be the first to know about sales and special discounts.