TinyPNG批量壓縮腳本

TinyPNG 提供了 API,你可以使用它來批量壓縮圖片。以下是一個(gè)簡(jiǎn)單的 Python 腳本示例,演示如何使用 TinyPNG 的 API 批量壓縮圖片:

首先,你需要在 TinyPNG 的網(wǎng)站上注冊(cè)賬號(hào)并獲取 API 密鑰。然后,你可以使用以下腳本:

import tinify
import os

# 設(shè)置 TinyPNG API 密鑰
tinify.key = "kX53y2cF4QlJsngZ57w17BfhYDF66Hr1tYm1232313"

# 設(shè)置要壓縮的圖片文件夾路徑
input_folder = "/Users/lvxuming/Desktop/HHKB/圖片壓縮前路徑"

# 設(shè)置輸出文件夾路徑
output_folder = "/Users/lvxuming/Desktop/HHKB/圖片壓縮后路徑"

def compress_image(input_path, output_path):
    try:
        # 壓縮圖片
        source = tinify.from_file(input_path)
        source.to_file(output_path)
        print(f"已壓縮: {input_path}")
    except tinify.errors.AccountError as e:
        print(f"TinyPNG API 密鑰錯(cuò)誤或已超過限制。錯(cuò)誤信息: {e}")
    except tinify.errors.ClientError as e:
        print(f"壓縮圖片時(shí)發(fā)生客戶端錯(cuò)誤。錯(cuò)誤信息: {e}")
    except tinify.errors.ServerError as e:
        print(f"TinyPNG 服務(wù)器發(fā)生錯(cuò)誤。錯(cuò)誤信息: {e}")
    except tinify.errors.ConnectionError as e:
        print(f"連接到 TinyPNG 服務(wù)器時(shí)發(fā)生錯(cuò)誤。錯(cuò)誤信息: {e}")
    except Exception as e:
        print(f"發(fā)生未知錯(cuò)誤。錯(cuò)誤信息: {e}")

def batch_compress_images(input_folder, output_folder):
    # 確保輸出文件夾存在
    if not os.path.exists(output_folder):
        os.makedirs(output_folder)

    # 遍歷輸入文件夾中的所有圖片文件
    for filename in os.listdir(input_folder):
        if filename.endswith(('.png', '.jpg', '.jpeg')):
            input_path = os.path.join(input_folder, filename)
            output_path = os.path.join(output_folder, filename)

            # 壓縮圖片
            compress_image(input_path, output_path)

if __name__ == "__main__":
    batch_compress_images(input_folder, output_folder)
最后執(zhí)行下腳本代碼,壓縮成功
python script.py   

已壓縮: /Users/lvxuming/Desktop/HHKB/圖片壓縮前路徑/財(cái)富升級(jí)彈框_1@3x.png

?? 注意:每個(gè)月只有500張免費(fèi)

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

友情鏈接更多精彩內(nèi)容