Python

How to Convert Images to WebP Using Python and Pillow

Learn how to batch convert JPG, PNG, and other image formats to WebP using Python and the Pillow library. Includes compression settings, transparency handling, and automation scripts.

March 20, 20267 min read

Why Convert to WebP?

WebP is a modern image format developed by Google that provides superior compression compared to JPG and PNG. On average, WebP images are 25-35% smaller than JPGs at equivalent quality and support transparency like PNG but at a fraction of the file size.

For web developers and content creators, switching to WebP means:

  • Faster page load times
  • Lower bandwidth costs
  • Better Core Web Vitals scores
  • Support across all modern browsers

Prerequisites

Before we begin, make sure you have:

  • Python 3.8 or higher installed
  • pip (Python package manager)

Install the Pillow library:

pip install Pillow

Pillow is a fork of the Python Imaging Library (PIL) and provides easy-to-use image processing capabilities.

Basic Image to WebP Conversion

Here is the simplest way to convert an image to WebP:

from PIL import Image

def convert_to_webp(input_path, output_path, quality=80):

img = Image.open(input_path)

img.save(output_path, "WEBP", quality=quality)

print(f"Converted: {input_path} -> {output_path}")

# Usage

convert_to_webp("photo.jpg", "photo.webp")

The quality parameter ranges from 1 to 100. A value of 80 provides an excellent balance between file size and visual quality.

Handling Transparency (PNG to WebP)

PNG images often contain transparency (alpha channel). WebP supports transparency natively, so the conversion is straightforward:

from PIL import Image

def png_to_webp(input_path, output_path, quality=80):

img = Image.open(input_path)

# Ensure RGBA mode for transparency

if img.mode in ("RGBA", "LA") or (img.mode == "P" and "transparency" in img.info):

img = img.convert("RGBA")

img.save(output_path, "WEBP", quality=quality)

png_to_webp("logo.png", "logo.webp")

This preserves the transparent areas perfectly in the output WebP file.

Batch Conversion Script

To convert an entire folder of images at once:

import os

from PIL import Image

from pathlib import Path

def batch_convert(input_dir, output_dir, quality=80):

Path(output_dir).mkdir(parents=True, exist_ok=True)

supported = {".jpg", ".jpeg", ".png", ".bmp", ".tiff"}

converted = 0

for filename in os.listdir(input_dir):

ext = os.path.splitext(filename)[1].lower()

if ext not in supported:

continue

input_path = os.path.join(input_dir, filename)

output_name = os.path.splitext(filename)[0] + ".webp"

output_path = os.path.join(output_dir, output_name)

img = Image.open(input_path)

if img.mode in ("RGBA", "LA", "P"):

img = img.convert("RGBA")

else:

img = img.convert("RGB")

img.save(output_path, "WEBP", quality=quality)

converted += 1

print(f" Converted: {filename} -> {output_name}")

print(f"\nDone! Converted {converted} images.")

batch_convert("./images", "./images-webp", quality=85)

Comparing File Sizes

You can add a comparison to see how much space you save:

import os

def compare_sizes(original, converted):

orig_size = os.path.getsize(original)

conv_size = os.path.getsize(converted)

savings = ((orig_size - conv_size) / orig_size) * 100

print(f"Original: {orig_size / 1024:.1f} KB")

print(f"WebP: {conv_size / 1024:.1f} KB")

print(f"Savings: {savings:.1f}%")

Typical results:

FormatOriginal SizeWebP SizeSavings
JPG (high quality)2.4 MB1.6 MB33%
PNG (with alpha)1.8 MB0.5 MB72%
BMP (uncompressed)5.7 MB0.3 MB95%

FAQ

Does WebP work in all browsers?

Yes, as of 2024 all major browsers (Chrome, Firefox, Safari, Edge) support WebP. The only exception is very old browser versions.

What quality setting should I use?

For photographs, quality 75-85 is ideal. For graphics and illustrations, try 85-95. Below 70, you may notice visible artifacts.

Can I convert WebP back to JPG or PNG?

Yes, Pillow can open WebP files and save them in any supported format. You can also use Reformat's free online converter.

Try These Tools

Mentioned in this tutorial — free, no sign-up required.

pythonwebpimage-conversionpillow

Related Tutorials