使用 tinypng 脚本打包为exe 进行压缩图片

工作过程避免不了的使用到压缩图片,一直使用 tinify.cn/, 每次操作都会很麻烦, 就想着看看能不能通过api了,

由于最近换成了 windows系统, 就准备打包为 exe,

注意点:

  1. 通过使用 pip show tinify

查询 tinify 的位置, 然后找到 data 文件夹里面的 cacert.pem 文件, 将文件拷贝出来和脚本文件同级别

  1. 通过代码设置 cacert.pem 文件同级别保存

  2. 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

相关推荐
花酒锄作田5 小时前
[python]argparse 包在聊天机器人中的应用
python
NiceCloud喜云8 小时前
Opus 4.8 的 Effort Control 怎么选:Low 到 Max 五档策略
android·java·大数据·前端·c++·python·spring
wordbaby8 小时前
React Native + RNOH:跨页面数据回传的最佳实践与避坑指南
前端·react native
丷丩8 小时前
MapLibre GL JS第22课:查看本地GeoJSON
前端·javascript·map·mapbox·maplibre gl js
AI玫瑰助手8 小时前
Python函数:默认参数的定义与注意事项
开发语言·python·信息可视化
weixin_468466858 小时前
全局与局部注意力机制新手实战指南
人工智能·python·深度学习·算法·自然语言处理·transformer·注意力机制
小糖学代码9 小时前
LLM系列:环境搭建:5.Python-dotenv 环境变量管理
人工智能·python·深度学习·神经网络
智慧物业老杨9 小时前
智慧物业合同周期管理系统:从风险预警到智能交接的全流程数智化落地方案
java·人工智能·python
Front思9 小时前
AI前端工程师需要具备能力+
前端·人工智能·ai
橙橙笔记9 小时前
Python的学习第一部分
python·学习