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

相关推荐
Peter-Code1 小时前
Nginx 常用操作整理(前端)
服务器·前端·nginx
宿州派大星4 小时前
Python实战:PyQt5 + OpenCV + Dlib 打造AI桌面应用
人工智能·python·qt
承渊政道5 小时前
【从零开始大模型开发与微调:基于PyTorch与ChatGLM】(开源大模型ChatGLM高级定制化应用实战)
人工智能·pytorch·python·llm·模型微调·glm
Java后端的Ai之路11 小时前
06-React-Props
前端·react.js·前端框架
Smoothcloud润云11 小时前
PyTorch大模型权重加载与启动耗时优化实战:定位磁盘、内存与显存瓶颈
人工智能·pytorch·python·深度学习·gpu算力
Flynt12 小时前
开源"间谍卫星"说数据全是真的,我把它的免key数据源挨个试了一遍
前端·开源·数据可视化
databook12 小时前
从循环到向量化:NumPy提速的7个关键思维
python·数据分析·numpy
Csvn12 小时前
渲染管线
前端
棉猴12 小时前
玩游戏学Python1-Python和pgzero库的安装
python·pygame·玩游戏·pgzero·pgzrun
程序员大阳12 小时前
副队长CSS教程(33)–圆角与透明
前端·css·透明·圆角