Skip to content

Instantly share code, notes, and snippets.

@wiesty
Created November 4, 2024 13:30
Show Gist options
  • Select an option

  • Save wiesty/db26d9fb9ef384dec2e540a6bb1c645f to your computer and use it in GitHub Desktop.

Select an option

Save wiesty/db26d9fb9ef384dec2e540a6bb1c645f to your computer and use it in GitHub Desktop.
This script recursively converts JPEG, JPG, and PNG images in the current directory to WebP format, adjusting the quality to ensure each file remains under 1 MB in size.
import os
from PIL import Image
source_folder = os.getcwd()
target_folder = os.path.join(source_folder, "webp_converted")
if not os.path.exists(target_folder):
os.makedirs(target_folder)
max_file_size = 1 * 1024 * 1024
def convert_images_to_webp(source_folder, target_folder):
for root, _, files in os.walk(source_folder):
for file in files:
if file.lower().endswith(('.jpeg', '.jpg', '.png')):
source_path = os.path.join(root, file)
target_path = os.path.join(target_folder, os.path.splitext(file)[0] + ".webp")
try:
with Image.open(source_path) as img:
if img.mode in ('RGBA', 'LA') or (img.mode == 'P' and 'transparency' in img.info):
img = img.convert("RGBA")
else:
img = img.convert("RGB")
quality = 90
img.save(target_path, "webp", quality=quality)
while os.path.getsize(target_path) > max_file_size:
quality -= 5
if quality < 5:
print(f"Warning: {target_path} could not be compressed under 1 MB.")
break
img.save(target_path, "webp", quality=quality)
print(f"Converted: {source_path} -> {target_path} (Final quality: {quality})")
except Exception as e:
print(f"Error converting {source_path}: {e}")
convert_images_to_webp(source_folder, target_folder)
print("All images have been converted and saved in the target folder.")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment