1234567891011121314151617181920212223242526272829303132 |
- import os
- from PIL import Image
- import argparse
- def convert_to_webp(dir_path):
- for subdir, dirs, files in os.walk(dir_path):
- for file in files:
- filepath = subdir + os.sep + file
- if filepath.endswith(".webp"):
- continue
- try:
- img = Image.open(filepath)
- if img.format == "WEBP":
- continue
- webp_path = filepath + ".webp"
- img.save(webp_path, "WEBP")
- os.remove(filepath)
- os.rename(webp_path, filepath)
- except IOError:
- print(f"Cannot convert {file}")
- if __name__ == "__main__":
- parser = argparse.ArgumentParser(description='Convert images to webp format.')
- parser.add_argument('dir_path', type=str, help='Directory path to scan for images')
- args = parser.parse_args()
- convert_to_webp(args.dir_path)
- # python compress_dir_img.py /path/to/directory
|