memos_pic.py 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. import os
  2. import requests
  3. from PIL import Image
  4. # 压缩图片,然后更新数据库
  5. def convert_to_webp(dir_path):
  6. common_image_extensions = [".jpg", ".jpeg", ".png"]
  7. for subdir, dirs, files in os.walk(dir_path):
  8. # print(files)
  9. for file in files:
  10. filepath = subdir + os.sep + file
  11. # 如果不是指定格式图片,就不转换
  12. if not any(filepath.lower().endswith(ext) for ext in common_image_extensions):
  13. continue
  14. # 如果图片大小小于300k,就不转换
  15. img = Image.open(filepath)
  16. print("检测到其他格式图片:" + filepath)
  17. webp_path = filepath + ".webp"
  18. img.save(webp_path, "WEBP", quality=80)
  19. # 如果图片还是大于300K,就设置图片质量为50
  20. if os.path.getsize(webp_path) > 300 * 1024:
  21. img.save(webp_path, "WEBP", quality=30)
  22. os.remove(filepath)
  23. # 如果图片原始路径里面有assert,截取从assert开始的路径
  24. if "assets" in filepath:
  25. index = filepath.index("assets")
  26. filepath = filepath[index:]
  27. # https://web_history.tianyunperfect.cn/memos/update_resource
  28. # get original_internal_path: str, new_internal_path: str
  29. original_internal_path = filepath
  30. new_internal_path = filepath + ".webp"
  31. print(original_internal_path, new_internal_path)
  32. res = requests.get(f"https://web_history.tianyunperfect.cn/memos/update_resource?original_internal_path={original_internal_path}&new_internal_path={new_internal_path}",
  33. verify=False)
  34. print(res.json())
  35. # if __name__ == "__main__":
  36. # parser = argparse.ArgumentParser(description='Convert images to webp format.')
  37. # parser.add_argument('dir_path', type=str, help='Directory path to scan for images')
  38. #
  39. # args = parser.parse_args()
  40. #
  41. # convert_to_webp(args.dir_path)
  42. ## python compress_dir_img.py /path/to/directory
  43. # convert_to_webp("/Users/alvin/Desktop/tmp2")
  44. convert_to_webp("/app/memos/assets")