123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354 |
- import os
- import requests
- from PIL import Image
- # 压缩图片,然后更新数据库
- def convert_to_webp(dir_path):
- 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
- # 如果不是指定格式图片,就不转换
- if not any(filepath.lower().endswith(ext) for ext in common_image_extensions):
- continue
- # 如果图片大小小于300k,就不转换
- img = Image.open(filepath)
- print("检测到其他格式图片:" + filepath)
- webp_path = filepath + ".webp"
- img.save(webp_path, "WEBP", quality=80)
- # 如果图片还是大于300K,就设置图片质量为50
- if os.path.getsize(webp_path) > 300 * 1024:
- img.save(webp_path, "WEBP", quality=30)
- os.remove(filepath)
- # 如果图片原始路径里面有assert,截取从assert开始的路径
- if "assets" in filepath:
- index = filepath.index("assets")
- filepath = filepath[index:]
- # https://web_history.tianyunperfect.cn/memos/update_resource
- # get original_internal_path: str, new_internal_path: str
- original_internal_path = filepath
- new_internal_path = filepath + ".webp"
- print(original_internal_path, new_internal_path)
- res = requests.get(f"https://web_history.tianyunperfect.cn/memos/update_resource?original_internal_path={original_internal_path}&new_internal_path={new_internal_path}",
- verify=False)
- print(res.json())
- # 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("/Users/alvin/Desktop/tmp2")
- convert_to_webp("/app/memos/assets")
|