温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

使用 tinypng怎么实现批量压缩

发布时间:2021-08-10 17:36:31 来源:亿速云 阅读:159 作者:Leah 栏目:编程语言

使用 tinypng怎么实现批量压缩,相信很多没有经验的人对此束手无策,为此本文总结了问题出现的原因和解决方法,通过这篇文章希望你能解决这个问题。

直接上代码:

# -*- coding: utf-8 -*-

"""脚本功能说明:使用 tinypng,一键批量压缩指定文件(夹)所有文件"""

import os
import sys
import tinify

tinify.key = "你自己申请的 key" # AppKey

def get_file_dir(file):
    """获取文件目录通用函数"""
    fullpath = os.path.abspath(os.path.realpath(file))
    return os.path.dirname(fullpath)

def check_suffix(file_path):
    """检查指定文件的后缀是否符合要求"""
    file_path_lower = file_path.lower()
    return (file_path_lower.endswith('.png')
            or file_path_lower.endswith('.jpg')
            or file_path_lower.endswith('.jpeg'))

def compress_by_tinypng(input_file):
    """使用 tinypng 进行压缩,中文前面的 u 是为了兼容 py2.7"""
    if not check_suffix(input_file):
        print(u'只支持png\\jpg\\jepg格式文件:' + input_file)
        return

    file_name = os.path.basename(input_file)
    output_path = os.path.join(get_file_dir(sys.argv[0]), 'tinypng')
    output_file = os.path.join(output_path, file_name)
    print(output_file)
    if not os.path.isdir(output_path):
        os.makedirs(output_path)

    try:
        source = tinify.from_file(input_file)
        source.to_file(output_file)
        print(u'文件压缩成功:' + input_file)
        old_size = os.path.getsize(input_file)
        print(u'压缩前文件大小:%d 字节' % old_size)
        new_size = os.path.getsize(output_file)
        print(u'文件保存地址:%s' % output_file)
        print(u'压缩后文件大小:%d 字节' % new_size)
        print(u'压缩比: %d%%' % ((old_size - new_size) * 100 / old_size))
    except tinify.errors.AccountError:
        print(u'Key 使用量已超,请更新 Key,并使用命令[Usage] %s [filepath] [key]运行'
              % os.path.basename(sys.argv[0]))

def check_path(input_path):
    """如果输入的是文件则直接压缩,如果是文件夹则先遍历"""
    if os.path.isfile(input_path):
        compress_by_tinypng(input_path)
    elif os.path.isdir(input_path):
        dirlist = os.walk(input_path)
        for root, dirs, files in dirlist:
            for filename in files:
                compress_by_tinypng(os.path.join(root, filename))
    else:
        print(u'目标文件(夹)不存在,请确认后重试。')

if __name__ == '__main__':
    len_param = len(sys.argv)
    if len_param != 2 and len_param != 3:
        print('[Usage] %s [filepath]' % os.path.basename(sys.argv[0]))
    elif len_param == 3:
        tinify.key = sys.argv[2]
        check_path(sys.argv[1])
    else:
        check_path(sys.argv[1])

使用说明

1. 请先安装 tinify 的依赖库:
python -m pip install tinify
2. 申请 tinify key

到 https://tinypng.com/developers 申请自己的 key,每个 key 每个月可以压缩 500 个文件。

3. 执行脚本

申请完 key 之后,更新到代码段中的:

tinify.key = "your key" # AppKey

然后带参数执行脚本即可。

带的第一个参数是必选的,可以是文件,也可以是文件夹。

第二个参数是可选的,自定义 key,如果输入了第三个参数,则优先使用自定义 key。

压缩后的文件,默认输出到当前脚本所在目录下的 tinypng 文件夹中,如果要输出到其他位置,可以自行修改脚本实现。

看完上述内容,你们掌握使用 tinypng怎么实现批量压缩的方法了吗?如果还想学到更多技能或想了解更多相关内容,欢迎关注亿速云行业资讯频道,感谢各位的阅读!

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI