使用 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])python -m pip install tinify
到 https://tinypng.com/developers 申請自己的 key,每個 key 每個月可以壓縮 500 個文件。
申請完 key 之后,更新到代碼段中的:
tinify.key = "your key" # AppKey
然后帶參數執行腳本即可。
帶的第一個參數是必選的,可以是文件,也可以是文件夾。
第二個參數是可選的,自定義 key,如果輸入了第三個參數,則優先使用自定義 key。
壓縮后的文件,默認輸出到當前腳本所在目錄下的 tinypng 文件夾中,如果要輸出到其他位置,可以自行修改腳本實現。
看完上述內容,你們掌握使用 tinypng怎么實現批量壓縮的方法了嗎?如果還想學到更多技能或想了解更多相關內容,歡迎關注創新互聯行業資訊頻道,感謝各位的閱讀!
另外有需要云服務器可以了解下創新互聯scvps.cn,海內外云服務器15元起步,三天無理由+7*72小時售后在線,公司持有idc許可證,提供“云服務器、裸金屬服務器、高防服務器、香港服務器、美國服務器、虛擬主機、免備案服務器”等云主機租用服務以及企業上云的綜合解決方案,具有“安全穩定、簡單易用、服務可用性高、性價比高”等特點與優勢,專為企業上云打造定制,能夠滿足用戶豐富、多元化的應用場景需求。
網站欄目:使用tinypng怎么實現批量壓縮-創新互聯
網頁URL:http://www.js-pz168.com/article10/dscodo.html
成都網站建設公司_創新互聯,為您提供App開發、微信小程序、自適應網站、電子商務、網站制作、建站公司
聲明:本網站發布的內容(圖片、視頻和文字)以用戶投稿、用戶轉載內容為主,如果涉及侵權請盡快告知,我們將會在第一時間刪除。文章觀點不代表本網站立場,如需處理請聯系客服。電話:028-86922220;郵箱:631063699@qq.com。內容未經允許不得轉載,或轉載時需注明來源: 創新互聯