52 lines
1.8 KiB
Python
52 lines
1.8 KiB
Python
import os
|
|
from PIL import Image
|
|
|
|
def convert_images_to_webp(directory):
|
|
"""
|
|
Converts all image files in the specified directory to webp format.
|
|
|
|
Args:
|
|
directory (str): The path to the directory containing the image files to convert.
|
|
"""
|
|
try:
|
|
# Supported image extensions
|
|
supported_extensions = [".jpg", ".jpeg", ".png", ".bmp", ".tiff"]
|
|
|
|
# List all files in the directory
|
|
files = [f for f in os.listdir(directory) if os.path.isfile(os.path.join(directory, f))]
|
|
|
|
if not files:
|
|
print("No files found in the directory.")
|
|
return
|
|
|
|
for file_name in files:
|
|
# Get the file extension
|
|
file_extension = os.path.splitext(file_name)[1].lower()
|
|
if file_extension not in supported_extensions:
|
|
continue # Skip unsupported files
|
|
|
|
# Open the image
|
|
old_path = os.path.join(directory, file_name)
|
|
try:
|
|
with Image.open(old_path) as img:
|
|
# Construct the new file name
|
|
new_name = os.path.splitext(file_name)[0] + ".webp"
|
|
new_path = os.path.join(directory, new_name)
|
|
# Save as webp
|
|
img.save(new_path, "webp")
|
|
print(f"Converted: {old_path} -> {new_path}")
|
|
except Exception as e:
|
|
print(f"Failed to convert {file_name}: {e}")
|
|
|
|
print("All supported images have been converted to webp format.")
|
|
except Exception as e:
|
|
print(f"An error occurred: {e}")
|
|
|
|
# Example usage
|
|
if __name__ == "__main__":
|
|
folder_path = input("Enter the path to the folder: ").strip()
|
|
if os.path.isdir(folder_path):
|
|
convert_images_to_webp(folder_path)
|
|
else:
|
|
print("The provided path is not a valid directory.")
|