使用 Python 脚本调用 tinypng 递归批量压缩目录下的图片

153次阅读
没有评论

共计 1717 个字符,预计需要花费 5 分钟才能阅读完成。

TinyPNG 是提供在线图片压缩服务的网站,可以帮助用户将 PNG 、JPEG、webp 格式的图片压缩到更小的文件大小,而且不会显著影响图片的质量。TinyPNG 可以有效地减小图片的文件大小,从而使网站的加载速度更快,用户的流量更少,并提高用户的访问体验。

最大的优点就是几乎无损压缩!!!官网在线体验:https://tinypng.com/

除了网页的方式,还提供了 api 方式进行压缩,本脚本就是使用 api 进行调用。免费的每个月有 500 的额度,调用 api 需要 key,在网站 https://tinify.com/dashboard/api 获取,需要先进行用户注册。

compress.py

import os
import tinify

tinify.key = "your_api_key_here"
directory = "/path/to/directory"  # Set the directory here

def format_size(size):
    # Convert size in bytes to human-readable format
    for unit in ["B", "KB", "MB", "GB", "TB"]:
        if size < 1024.0:
            return f"{size:.1f} {unit}"
        size /= 1024.0

def compress_images_in_directory():
    original_total_size = 0
    compressed_total_size = 0
    for root, dirs, files in os.walk(directory):
        for file in files:
            if file.endswith(".jpg") or file.endswith(".png") or file.endswith(".webp"):
                # Get the size of the original image file
                file_path = os.path.join(root, file)
                original_size = os.path.getsize(file_path)
                original_total_size += original_size
                original_size_str = format_size(original_size)

                # Compress the image using Tinify
                source = tinify.from_file(file_path)
                source.to_file(file_path)

                # Get the size of the compressed image file
                compressed_size = os.path.getsize(file_path)
                compressed_total_size += compressed_size
                compressed_size_str = format_size(compressed_size)

                # Print the compression log
                print(f"已压缩文件 {file_path} ({original_size_str} -> {compressed_size_str})")

    # Print the compression summary
    original_total_size_str = format_size(original_total_size)
    compressed_total_size_str = format_size(compressed_total_size)
    saved_space_str = format_size(original_total_size - compressed_total_size)
    print(f"压缩前总占用空间: {original_total_size_str}")
    print(f"压缩后总占用空间: {compressed_total_size_str}")
    print(f"已节省空间: {saved_space_str}")

if __name__ == "__main__":
    compress_images_in_directory()

使用这个脚本,只需要修改 tinypng 的 key,以及想要递归压缩的根目录。

python3 compress.py

脚本测试:

使用 Python 脚本调用 tinypng 递归批量压缩目录下的图片

提醒:本文发布于381天前,文中所关联的信息可能已发生改变,请知悉!

AD:【腾讯云服务器大降价】2核4G 222元/3年 1核2G 38元/年
正文完
 
阿蛮君
版权声明:本站原创文章,由 阿蛮君 2023-03-13发表,共计1717字。
转载说明:除特殊说明外本站文章皆由CC-4.0协议发布,转载请注明出处。
评论(没有评论)
Copyright © 2022-2024 阿蛮君博客 湘ICP备2023001393号
本网站由 亿信互联 提供云计算服务 | 无忧云 提供安全防护和加速服务