繼昨天做好tinify壓縮腳本后眷蜓,就在考慮能不能直接遍歷找到Assets里的圖片進(jìn)行壓縮后替換原路徑。所以做了嘗試果然可以胎围。下面這句可以修改各種圖片范圍吁系。因我腳本是有個(gè)從大到小的圖片排序德召。所以會(huì)優(yōu)先從最大的開始?jí)嚎s。
# 選擇前500張圖片
selected_image_paths = sorted_image_paths[539:1039]
import tinify
import os
from PIL import Image
# 設(shè)置 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} 時(shí)出現(xiàn)錯(cuò)誤: {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("未找到任何圖片.")