123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566 |
- import os
- from PIL import Image
- import argparse
- from pybloom_live import ScalableBloomFilter
- def convert_to_webp(dir_path):
- path = "~/bf.bloom"
- path_expanduser = os.path.expanduser("%s" % path)
- if os.path.exists(path_expanduser):
- # 从 ~/bf.bloom 中读取bf
- bf = ScalableBloomFilter.fromfile(open(path_expanduser, "rb"))
- else:
- # 初始化一个布隆过滤器
- bf = ScalableBloomFilter(initial_capacity=100000, error_rate=0.001)
- common_image_extensions = [".jpg", ".jpeg", ".png"]
- for subdir, dirs, files in os.walk(dir_path):
- print(files)
- for file in files:
- filepath = subdir + os.sep + file
- # bf 校验
- if filepath in bf:
- continue
- # 如果已经转换过了,就不转换
- if filepath.endswith(".webp"):
- bf.add(filepath)
- continue
- # 如果不是图片,就不转换
- if not any(filepath.lower().endswith(ext) for ext in common_image_extensions):
- bf.add(filepath)
- continue
- # 如果图片大小小于500k,就不转换
- if os.path.getsize(filepath) < 500 * 1024:
- # 加入过滤器
- bf.add(filepath)
- continue
- try:
- img = Image.open(filepath)
- if img.format == "WEBP":
- bf.add(filepath)
- continue
- print("检测到其他格式图片:" + filepath)
- webp_path = filepath + ".webp"
- img.save(webp_path, "WEBP", quality=80)
- os.remove(filepath)
- os.rename(webp_path, filepath)
- # 加入过滤器
- bf.add(filepath)
- except IOError:
- print(f"Cannot convert {file}")
- # 保存bf到 ~/bf.bloom
- bf.tofile(open(path_expanduser, "wb"))
- # 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
- convert_to_webp("/c/Users/admin")
|