Skip to content

XiaomingX/png2webp-python

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

2 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

png2webp-python

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.

📋 Features

  • 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 .png with .webp).
  • Error Handling: Catches common issues (missing files, non-PNG inputs) with clear feedback.
  • Lightweight: Relies only on the Pillow library (no heavy dependencies).

🚀 Installation

  1. Prerequisite: Python 3.6+ (tested on 3.8-3.12).
  2. Install Dependencies: The tool uses Pillow (Python Imaging Library) for image processing. Install it via pip:
# Install Pillow (for image handling)
pip install pillow

# If you have multiple Python versions, use pip3 explicitly (e.g., Linux/macOS)
pip3 install pillow
  1. Clone the Repository:
git clone https://github.com/your-username/png2webp-python.git
cd png2webp-python

🔧 Quick Usage

1. Convert a Single PNG File

Use 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)

Command-Line Shortcut

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 60

2. Batch Convert All PNGs in a Folder

Extend 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 Details

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)

❓ Common Issues & Fixes

1. "ModuleNotFoundError: No module named 'PIL'"

  • Fix: Ensure Pillow is installed correctly. Run pip uninstall pillow then pip install pillow to re-install.

2. Transparent PNGs lose transparency (background becomes white)

  • 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.py by 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

3. "FileNotFoundError: File does not exist"

  • Fix: Double-check the file_path or folder_path (use absolute paths if relative paths cause issues, e.g., C:/Users/Name/images/logo.png on Windows or /home/name/images/logo.png on Linux).

📄 License

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.

🤝 Contributing

Contributions are welcome! Here’s how to help:

  1. Fork the repository.
  2. Create a feature branch (git checkout -b feature/batch-conversion).
  3. Commit your changes (git commit -m "Add batch conversion support").
  4. Push to the branch (git push origin feature/batch-conversion).
  5. Open a Pull Request.

Please ensure your code follows PEP 8 style guidelines and includes tests for new features.

🙏 Acknowledgements

  • 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.

About

PNG 转 WebP 的 Python 工具

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages