使用 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

相关推荐
子兮曰1 天前
jev-ultrafast 深度解析:7 秒订机票的浏览器 Agent 是如何炼成的
前端·后端·agent
子兮曰1 天前
Jev 爆发一周:7 秒 Agent 背后的 System One 生态与三场争议
前端·后端·ai编程
默_笙1 天前
🍙 给每个请求过安检:FastAPI 是怎么把校验写进类型注解的
python
前端小万1 天前
写公众号赚了 3000 块后,我做了一款叫 "一键成稿" 的软件
前端·微信小程序
爱勇宝1 天前
ZCode 开源 24 小时:一份没有历史的账本,回答不了"有没有偷代码"
前端·后端·chatglm (智谱)
qq_426003961 天前
启动playwright录制codegen生成自动化测试脚本
python·自动化
虎头金猫1 天前
4K 视频总卡在公网带宽?用 N1 + OpenList 把网盘播放链路重新理顺
运维·服务器·网络·python·容器·beautifulsoup·pandas
三十而立洋1 天前
Cookie 详解:从产生到安全,一次讲透
前端·javascript
长沙三为智能科技1 天前
家政小程序开发从0到上线:五阶段交付流程与验收清单
python
伞伞悦读1 天前
【第38期】Python 模块与包详解:import、from、模块搜索路径、包结构和 __init__
开发语言·python