tinypng压缩脚本
⚡ 首页 / 📁 工具 / 正文

tinypng压缩脚本

# 工具

tinypng官网

压缩Python脚本

import tinify
import os

tinify.key = "YOUR TINYPNG KEY"


def resize_image(input_file_path, output_file_path, target_width):
    source = tinify.from_file(input_file_path)
    resized = source.resize(method="scale", width=target_width)
    resized.to_file(output_file_path)

def resize_images_in_folder(input_folder, output_folder, target_width):
    if not os.path.exists(output_folder):
        os.makedirs(output_folder)
    
    for root, dirs, files in os.walk(input_folder):
        for file in files:
            if file.lower().endswith(('.jpg', '.jpeg', '.png', '.gif', '.bmp')):
                input_file_path = os.path.join(root, file)
                relative_path = os.path.relpath(input_file_path, input_folder)
                output_file_path = os.path.join(output_folder, relative_path)
                
                output_file_dir = os.path.dirname(output_file_path)
                if not os.path.exists(output_file_dir):
                    os.makedirs(output_file_dir)
                
                print(f"Resizing {input_file_path}...")
                resize_image(input_file_path, output_file_path, target_width)
                print(f"Saved resized image to {output_file_path}")

if __name__ == "__main__":
    input_folder = "./src"  # 替换为你的输入文件夹路径
    output_folder = "./dist"  # 替换为你的输出文件夹路径
    target_width = 1500  # 目标宽度(像素)

    resize_images_in_folder(input_folder, output_folder, target_width)

💬 评论交流 1

发表评论
贺某
贺某

🐮🍺