Created
February 7, 2025 07:05
-
-
Save ragingbal/3fa984eeb3d62f41966c15360686116e to your computer and use it in GitHub Desktop.
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
# brew install webp | |
# then run following | |
import os | |
import subprocess | |
import argparse | |
def convert_png_to_webp(directory): | |
""" | |
Converts PNG images in a directory to WebP format. | |
Args: | |
directory: The directory containing the PNG images. | |
""" | |
if not os.path.isdir(directory): | |
print(f"Error: '{directory}' is not a valid directory.") | |
return | |
for filename in os.listdir(directory): | |
if filename.lower().endswith(".png"): | |
input_path = os.path.join(directory, filename) | |
base, ext = os.path.splitext(filename) | |
output_path = os.path.join(directory, f"{base}.webp") | |
try: | |
# Construct the command, crucial for error handling | |
command = ["cwebp", input_path, "-o", output_path] | |
# Use subprocess.run for better error handling and output capture: | |
result = subprocess.run(command, capture_output=True, text=True, check=True) | |
print(f"Converted {filename} to {output_path}") | |
except FileNotFoundError: | |
print(f"Error: cwebp not found in your system's PATH. Please ensure cwebp is installed and in your PATH.") | |
return | |
except subprocess.CalledProcessError as e: | |
print(f"Error converting {filename}: {e.stderr}") | |
if __name__ == "__main__": | |
parser = argparse.ArgumentParser(description="Convert PNG images to WebP in a directory.") | |
parser.add_argument("directory", help="The directory containing PNG images.") | |
args = parser.parse_args() | |
convert_png_to_webp(args.directory) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment