Created
November 13, 2023 02:33
-
-
Save iskakaushik/187454272cb212ffceb30a3edff17b0e to your computer and use it in GitHub Desktop.
Convert images to webp for better size
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import os | |
import glob | |
from PIL import Image | |
from concurrent.futures import ThreadPoolExecutor | |
import logging | |
# Setup logging | |
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s') | |
def convert_image_to_webp(img_path): | |
try: | |
with Image.open(img_path) as img: | |
# Convert image to webp | |
webp_path = os.path.splitext(img_path)[0] + '.webp' | |
img.save(webp_path, 'webp') | |
# Delete the original file | |
os.remove(img_path) | |
logging.info(f"Converted and deleted: {img_path}") | |
except Exception as e: | |
logging.error(f"Error processing {img_path}: {e}") | |
def convert_to_webp(directory): | |
# Change working directory to the specified path | |
os.chdir(directory) | |
# Prepare list of all jpg/jpeg files (case-insensitive) | |
image_files = [] | |
for ext in ('*.jpg', '*.JPG', '*.jpeg', '*.JPEG'): | |
image_files.extend(glob.glob(ext, recursive=True)) | |
logging.info(f"Found {len(image_files)} images to convert.") | |
# Use 16 threads to process the images | |
with ThreadPoolExecutor(max_workers=16) as executor: | |
executor.map(convert_image_to_webp, image_files) | |
# Replace './' with your directory path or keep it to use the current directory | |
convert_to_webp('./') | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment