Python · Tools

Bulk Compress & Convert Images with Python

Got a folder full of heavy JPGs and PNGs? This short Python script compresses them all and converts them to WebP in one run — perfect for speeding up a website or shrinking a photo archive.

Bulk compress images with Python

1. Install Pillow

Pillow is Python’s friendly imaging library. Install it with pip:

pip install Pillow

2. The script

Put your images in an images folder next to the script, then run it. Compressed WebP files land in a compressed folder.

import os


from PIL import Image





INPUT_DIR = "images"


OUTPUT_DIR = "compressed"


QUALITY = 80          # 75-85 is the sweet spot


MAX_WIDTH = 1920      # downscale anything wider than this





os.makedirs(OUTPUT_DIR, exist_ok=True)





for name in os.listdir(INPUT_DIR):


    if not name.lower().endswith((".jpg", ".jpeg", ".png")):


        continue





    img = Image.open(os.path.join(INPUT_DIR, name)).convert("RGB")





    # optional: resize very large images


    if img.width > MAX_WIDTH:


        ratio = MAX_WIDTH / img.width


        img = img.resize((MAX_WIDTH, int(img.height * ratio)))





    out_name = os.path.splitext(name) + ".webp"


    img.save(os.path.join(OUTPUT_DIR, out_name), "WEBP", quality=QUALITY)


    print(f"Compressed {name} -> {out_name}")





print("All done.")

3. Tweak it

  • QUALITY — lower means smaller files. 80 is a safe default.
  • MAX_WIDTH — resize huge images so you are not serving 4000px photos.
  • Change "WEBP" to "JPEG" if you need JPGs instead.

Want it fully automated?

I build small automations and web tools that handle this kind of repetitive work for you — on a schedule, in the cloud, or right inside your website’s upload flow.

Ask us anything×