compress_dir_img.py 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. import os
  2. from PIL import Image
  3. import argparse
  4. from pybloom_live import ScalableBloomFilter
  5. def convert_to_webp(dir_path):
  6. path = "~/bf.bloom"
  7. path_expanduser = os.path.expanduser("%s" % path)
  8. if os.path.exists(path_expanduser):
  9. # 从 ~/bf.bloom 中读取bf
  10. bf = ScalableBloomFilter.fromfile(open(path_expanduser, "rb"))
  11. else:
  12. # 初始化一个布隆过滤器
  13. bf = ScalableBloomFilter(initial_capacity=100000, error_rate=0.001)
  14. common_image_extensions = [".jpg", ".jpeg", ".png"]
  15. for subdir, dirs, files in os.walk(dir_path):
  16. print(files)
  17. for file in files:
  18. filepath = subdir + os.sep + file
  19. # bf 校验
  20. if filepath in bf:
  21. continue
  22. # 如果已经转换过了,就不转换
  23. if filepath.endswith(".webp"):
  24. bf.add(filepath)
  25. continue
  26. # 如果不是图片,就不转换
  27. if not any(filepath.lower().endswith(ext) for ext in common_image_extensions):
  28. bf.add(filepath)
  29. continue
  30. # 如果图片大小小于500k,就不转换
  31. if os.path.getsize(filepath) < 500 * 1024:
  32. # 加入过滤器
  33. bf.add(filepath)
  34. continue
  35. try:
  36. img = Image.open(filepath)
  37. if img.format == "WEBP":
  38. bf.add(filepath)
  39. continue
  40. print("检测到其他格式图片:" + filepath)
  41. webp_path = filepath + ".webp"
  42. img.save(webp_path, "WEBP", quality=80)
  43. os.remove(filepath)
  44. os.rename(webp_path, filepath)
  45. # 加入过滤器
  46. bf.add(filepath)
  47. except IOError:
  48. print(f"Cannot convert {file}")
  49. # 保存bf到 ~/bf.bloom
  50. bf.tofile(open(path_expanduser, "wb"))
  51. if __name__ == "__main__":
  52. parser = argparse.ArgumentParser(description='Convert images to webp format.')
  53. parser.add_argument('dir_path', type=str, help='Directory path to scan for images')
  54. args = parser.parse_args()
  55. convert_to_webp(args.dir_path)
  56. ## python compress_dir_img.py /path/to/directory
  57. # convert_to_webp("/c/Users/admin")