工作过程避免不了的使用到压缩图片,一直使用 tinify.cn/, 每次操作都会很麻烦, 就想着看看能不能通过api了,
由于最近换成了 windows系统, 就准备打包为 exe,
注意点:
- 通过使用 pip show tinify
查询 tinify 的位置, 然后找到 data 文件夹里面的 cacert.pem 文件, 将文件拷贝出来和脚本文件同级别
-
通过代码设置 cacert.pem 文件同级别保存
-
key 可以通过 tinify.com/dashboard/a..., 自己去创建
lua
os.environ["REQUESTS_CA_BUNDLE"] = os.path.join(
os.path.dirname(sys.argv[0]), "cacert.pem"
)
python
# -*- coding: utf-8 -*-
import tinify, os, sys
import requests
import datetime
tinify.key = "xxxxxxxxx" # 自己去创建一个的吧
cacert = os.path.join(os.getcwd(), "cacert.pem")
# tinify.get_client.session.verify = cacert
os.environ["REQUESTS_CA_BUNDLE"] = os.path.join(
os.path.dirname(sys.argv[0]), "cacert.pem"
)
"""
压缩图片spng"
"""
def compress_image(input_path, output_path=None):
if not output_path:
fileDir = os.path.dirname(input_path)
filename = os.path.basename(input_path)
output_path = os.path.join(fileDir, newDir, filename)
# print(f"正在处理图片1: {input_path}")
# print(f"正在处理图片2: {output_path}")
try:
source = tinify.from_file(input_path)
source.to_file(output_path)
print(f"压缩前: {logTips(input_path)} {input_path}")
print(f"压缩后: {logTips(output_path)} {output_path}")
except tinify.Error as e:
print(f"压缩失败: {e} 图片:{input_path}")
"""
根据图片路径,计算并返回图片的大小。
"""
def logTips(img_path_compress: str):
# 压缩后图片大小
img_compress_size = os.path.getsize(img_path_compress) / 1024
return str(int(img_compress_size)) + "KB"
"""
确认是否压缩所有的图片
"""
def compress_all_img(img_path: str):
isAll = input("是否确认压缩所有的后缀为png/jpg/jpeg的图片 ?(y/n)\n")
if isAll.lower() == "y":
lst = os.listdir(img_path)
idx = 0
for img in lst:
img_path_compress = os.path.join(img_path, img)
if img.endswith(".png") or img.endswith(".jpg") or img.endswith(".jpeg"):
idx += 1
print(f"正在处理第 {idx} 张图片:")
compress_image(img_path_compress)
else:
print("取消操作")
def compression_count():
compressions_this_month = tinify.compression_count
print(f"当前 key 共计使用了:{compressions_this_month}/500")
input("点击任意键退出程序\n")
if __name__ == "__main__":
args = sys.argv[1:] # 忽略第一个参数(脚本名称)
# current_dir = os.path.dirname(__file__)
current_dir = os.getcwd()
newDir = datetime.datetime.now().strftime("%Y-%m-%d %H-%M-%S")
if not os.path.exists(os.path.join(current_dir, newDir)):
os.mkdir(os.path.join(current_dir, newDir))
if not args:
compress_all_img(current_dir)
else:
for input_file in args:
full_input_path = os.path.join(current_dir, input_file)
if os.path.exists(full_input_path):
compress_image(full_input_path)
else:
print(f"文件不存在: {full_input_path}")
compression_count()
"""
参考文档:
https://blog.csdn.net/whatday/article/details/109138454
参考:
pyinstaller -F -w -i 图标.ico your_script.py
-F: 将所有文件打包成一个独立的可执行文件。
-w: 隐藏命令行窗口(适用于 GUI 程序)。
-i: 设置可执行文件的图标。
pyinstaller -y -F -n tinypng tinypng.py
打包命令行:
pyinstaller -y -F -n tinypng tinypng.py
pyinstaller -y -F -i favicon.ico -n tinypng tinypng.py
"""
End