Compress Images Using Python: Image Optimization Guide

If you want to Compress Images Using Python, then you are on the right platform. You can reduce the size of big photos in no time without harming their appearance. Smaller images speed up loading web pages, lighten the weight of emails, and fit within upload limits. This tutorial will walk you through how to practically take advantage of Pillow for compressing images while still controlling the image’s quality.

We will cover Python Image Compression basics, some simple scripts that you could reuse, and image optimization in Python for real projects, such as blogs, stores, and portfolios.

Pillow Setup and installation

Pillow is the ready to use imaging library in Python. With Pillow you canopen, process, and save formats like JPEG and PNG. You’ll adjust quality, optimize metadata, and resize images with a few lines of code. Before moving further into example, you need to install this library using below command:

pip install Pillow

Once installed, you can verify installation by below script and it will print it’s version:

import PIL
print(PIL.__version__)

Why Compress Images Using Python?

  • Speed up your website and improve Core Web Vitals
  • Email or chat images without hitting size limits
  • Cut storage and CDN costs
  • Prep photos for marketplaces or portfolio sites

Let’s see few different way or examples to compress images in Python.

Quick JPEG files compression with quality in Python

Generally, images captured from camera or created creative images like banners are stored into JPEG format. Which provide higher quality but grater in size. Compression can be helpful to optimize those images for any platform. Let’s take an example to JPEG image compression in Python:

from PIL import Image

img = Image.open("input.jpg")
img.save("output.jpg", quality=80, optimize=True)

Here, we have input image and we are creating new image file with reduced quality. The idle quality and compression size is 85. If you need more savings, you can try 70–75 but it’s not recommended for regular cases.

Lossless PNG compression for icons and UI

Sometimes, for assets like logo, icons or graphics with high value you need to keep them pixel perfect. With compression it can be harmful for quality. In these cases lossless PNG compression is useful.

from PIL import Image

img = Image.open("input.png")
img.save("output.png", optimize=True, compress_level=9)

In above example, it process file for optimization but the actual view is not being compromized.

Resize then compress for the web

Resize and compress can be used in websites where you need to show same image with different sizes. The Pillow library supports resize and with adding compression to that can help you to optimize image specially for websites. Below is example for resize and compress images with python pillow library:

from PIL import Image

img = Image.open("hero.jpg")
img.thumbnail((1600, 1600))
img.save("hero-optimized.jpg", quality=85, optimize=True)

Here it will take image and resize it to 1600 * 1600 pixel size then perform compression.

Additional Example: Batch compress a folder

For performing compression automatically for all the image, you can create an script which automatically compress and optimize image file with python script.

from pathlib import Path
from PIL import Image

src = Path("images")
dst = Path("images-optimized")
dst.mkdir(exist_ok=True)

for p in src.glob("*.*"):
    if p.suffix.lower() not in {".jpg", ".jpeg", ".png"}:
        continue
    img = Image.open(p)
    out = dst / p.name
    if p.suffix.lower() in {".jpg", ".jpeg"}:
        img.save(out, quality=80, optimize=True)
    else:
        img.save(out, optimize=True, compress_level=9)

In above script, you will load and optimize image files from entire directory. With looping we are performing image compression using it’s extension or type.

Conclusion

You can compress images with Python in minutes by doing quality-based JPEG compression, use lossless PNG optimization for graphics, and resize to your real display sizes. It can help you with cutting storage and CDN costs for images for marketplaces or portfolio sites. Also read Extract Audio/Video Meta Data in Python to quickly grab duration, codec, and bitrate for easier media management.