A PNG to WEBP Converter With Python

PHOTO EMBED

Wed Jul 19 2023 14:53:32 GMT+0000 (Coordinated Universal Time)

Saved by @pythonHub #python #python-hub #day6

from PIL import Image
import os
from pathlib import Path

def compress_image(image_path:str) -> None:
    '''Takes up a PNG file, compresses it and converts it to a WEBP.
    Uses the pillow, pathlib and os module to do this.
    Args:
        image_path: The path to the image (str)'''
    try:
        compression_level = 6
        img_nm = Path(os.path.basename(image_path))
        compressed_png_path =Path(f"images_webp/{img_nm}")

        if not(os.path.exists(compressed_png_path.with_suffix(".webp"))):
            # opening image
            img = Image.open(Path(image_path))
            # compressing image
            img.save(compressed_png_path, format="png", optimize=True, compress_level=compression_level)
            # opening compressed image
            img_compressed = Image.open(compressed_png_path)
            # Convert the compressed PNG to WebP
            img_compressed.save(compressed_png_path.with_suffix(".webp"), format="webp")
            # removing the compressed PNG
            os.remove(compressed_png_path)
        else:
            print("File already exists")

    except FileNotFoundError as e:
        print(f"Error: {e}")

paths = Path("images").glob("**/*.png")
for path in paths:
    compress_image(str(path))
content_copyCOPY

https://python-hub.com/day-6-a-png-to-webp-converter-with-python/