A lightweight Python tool to convert PNG images to WebP format with customizable quality, designed for efficiency and ease of use. WebP format reduces file size significantly (often 25-50% smaller than PNG) while maintaining high visual quality, making it ideal for web optimization, app assets, and storage savings.
- Single/Batch Conversion: Convert individual PNG files or all PNGs in a folder.
- Transparent Channel Handling: Automatically processes PNG transparency (defaults to white background; easy to modify for alpha preservation).
- Quality Control: Adjust compression quality (0-100) to balance file size and image clarity.
- Preserve Filenames: Output WebP files retain the original PNG filename (only replaces
.pngwith.webp). - Error Handling: Catches common issues (missing files, non-PNG inputs) with clear feedback.
- Lightweight: Relies only on the
Pillowlibrary (no heavy dependencies).
- Prerequisite: Python 3.6+ (tested on 3.8-3.12).
- Install Dependencies: The tool uses
Pillow(Python Imaging Library) for image processing. Install it viapip:
# Install Pillow (for image handling)
pip install pillow
# If you have multiple Python versions, use pip3 explicitly (e.g., Linux/macOS)
pip3 install pillow- Clone the Repository:
git clone https://github.com/your-username/png2webp-python.git
cd png2webp-pythonUse the core function convert_png_to_webp() to convert one file. Example:
# Import the converter function
from png_to_webp import convert_png_to_webp
# Convert "example.png" to "example.webp" with quality 75 (0-100)
convert_png_to_webp(file_path="path/to/your/example.png", quality=75)Add this to a run.py file in the repo root for quick command-line use:
# run.py
from png_to_webp import convert_png_to_webp
import sys
if __name__ == "__main__":
if len(sys.argv) < 2:
print("Usage: python run.py <path-to-png-file> [quality]")
print("Example: python run.py ./images/photo.png 80")
sys.exit(1)
file_path = sys.argv[1]
quality = int(sys.argv[2]) if len(sys.argv) == 3 else 80 # Default quality: 80
convert_png_to_webp(file_path, quality)Run it from the terminal:
# Convert "photo.png" with default quality (80)
python run.py ./images/photo.png
# Convert with custom quality (60)
python run.py ./images/photo.png 60Extend the tool to process an entire directory (add this to run.py or a new batch_convert.py):
# batch_convert.py
from png_to_webp import convert_png_to_webp
import os
def batch_convert_png_to_webp(folder_path, quality=80):
"""Convert all PNG files in a folder to WebP."""
if not os.path.isdir(folder_path):
print(f"Error: '{folder_path}' is not a valid directory.")
return
# Iterate over all files in the folder
for filename in os.listdir(folder_path):
file_path = os.path.join(folder_path, filename)
# Skip directories and process only PNG files
if os.path.isfile(file_path) and filename.lower().endswith(".png"):
convert_png_to_webp(file_path, quality)
if __name__ == "__main__":
# Example: Convert all PNGs in the "input-images" folder with quality 70
target_folder = "./input-images" # Replace with your folder path
batch_convert_png_to_webp(target_folder, quality=70)Run batch conversion:
python batch_convert.py| Parameter | Type | Description | Default |
|---|---|---|---|
file_path |
String | Full/relative path to the input PNG file (e.g., ./assets/logo.png). |
Required |
quality |
Integer | Compression quality (0 = lowest quality/smallest file; 100 = highest quality/largest file). | 80 |
folder_path |
String | Path to the folder containing PNGs (for batch conversion). | Required (for batch) |
- Fix: Ensure
Pillowis installed correctly. Runpip uninstall pillowthenpip install pillowto re-install.
- Why: The default code converts transparent backgrounds to white for broader compatibility (some tools struggle with WebP alpha channels).
- Fix: To preserve transparency, modify the conversion logic in
png_to_webp.pyby removing the background handling:# Replace this block: if img.mode in ('RGBA', 'LA'): background = Image.new(img.mode[:-1], img.size, (255, 255, 255)) background.paste(img, img.split()[-1]) img = background # With: if img.mode in ('RGBA', 'LA'): # Preserve alpha channel for WebP pass
- Fix: Double-check the
file_pathorfolder_path(use absolute paths if relative paths cause issues, e.g.,C:/Users/Name/images/logo.pngon Windows or/home/name/images/logo.pngon Linux).
This project is licensed under the MIT License — see the LICENSE file for details. You’re free to use, modify, and distribute this tool for personal or commercial projects.
Contributions are welcome! Here’s how to help:
- Fork the repository.
- Create a feature branch (
git checkout -b feature/batch-conversion). - Commit your changes (
git commit -m "Add batch conversion support"). - Push to the branch (
git push origin feature/batch-conversion). - Open a Pull Request.
Please ensure your code follows PEP 8 style guidelines and includes tests for new features.
- Built with Pillow — the de facto Python library for image processing.
- Inspired by the need for simple, lightweight tools to optimize web assets without complex software.