美文网首页
利用tinify批量给iOS Assets.xcassets瘦身

利用tinify批量给iOS Assets.xcassets瘦身

作者: 林时工快睡觉 | 来源:发表于2024-01-16 10:33 被阅读0次

继昨天做好tinify压缩脚本后,就在考虑能不能直接遍历找到Assets里的图片进行压缩后替换原路径。所以做了尝试果然可以。下面这句可以修改各种图片范围。因我脚本是有个从大到小的图片排序。所以会优先从最大的开始压缩。

# 选择前500张图片
selected_image_paths = sorted_image_paths[539:1039]
import tinify
import os
from PIL import Image

# 设置 Tinify API 密钥
tinify.key = "sft1C3Z2MC40ZKw61k9fVJ1g3CcyHsr829d"

def compress_and_replace(image_path):
    try:
        # 使用 Tinify 压缩图片
        source = tinify.from_file(image_path)
        source.to_file(image_path)
        print(f"已压缩并替换图片: {image_path}")
    except tinify.Error as e:
        print(f"压缩图片 {image_path} 时出现错误: {e.message}")

def get_image_paths(asset_path):
    image_paths = []

    for root, dirs, files in os.walk(asset_path):
        for file in files:
            if file.endswith(('.png', '.jpg', '.jpeg')):
                image_paths.append(os.path.join(root, file))

    return image_paths

if __name__ == "__main__":
    xcode_project_path = "/Users/lvxuming/Desktop/Coding-不鸽"
    assets_path = os.path.join(xcode_project_path, "/Users/lvxuming/Desktop/Coding-不鸽/buge-main/BuGeElectricContest/BuGeElectricContest/Assets.xcassets")

    image_paths = get_image_paths(assets_path)

    if image_paths:
        # 按照文件大小从大到小排序
        sorted_image_paths = sorted(image_paths, key=lambda x: os.path.getsize(x), reverse=True)

        # 选择前500张图片
        selected_image_paths = sorted_image_paths[539:1039]

        for image_path in selected_image_paths:
            compress_and_replace(image_path)
    else:
        print("未找到任何图片.")

相关文章

网友评论

      本文标题:利用tinify批量给iOS Assets.xcassets瘦身

      本文链接:https://www.haomeiwen.com/subject/gadkodtx.html