compress_dir_img.py 969 B

1234567891011121314151617181920212223242526272829303132
  1. import os
  2. from PIL import Image
  3. import argparse
  4. def convert_to_webp(dir_path):
  5. for subdir, dirs, files in os.walk(dir_path):
  6. for file in files:
  7. filepath = subdir + os.sep + file
  8. if filepath.endswith(".webp"):
  9. continue
  10. try:
  11. img = Image.open(filepath)
  12. if img.format == "WEBP":
  13. continue
  14. webp_path = filepath + ".webp"
  15. img.save(webp_path, "WEBP")
  16. os.remove(filepath)
  17. os.rename(webp_path, filepath)
  18. except IOError:
  19. print(f"Cannot convert {file}")
  20. if __name__ == "__main__":
  21. parser = argparse.ArgumentParser(description='Convert images to webp format.')
  22. parser.add_argument('dir_path', type=str, help='Directory path to scan for images')
  23. args = parser.parse_args()
  24. convert_to_webp(args.dir_path)
  25. # python compress_dir_img.py /path/to/directory