import os
import glob
import subprocess
def optimize_image(image_path, max_size=500*1024):
优化图片文件大小
size = os.path.getsize(image_path)
if size <= max_size:
return False
file_ext = image_path.lower().split('.')[-1]
original_size_kb = size / 1024
根据格式选择优化策略
if file_ext in ['jpg', 'jpeg']:
cmd = [
'convert', image_path,
'-quality', '85%',
image_path + '.optimized'
]
elif file_ext == 'png':
cmd = [
'pngquant', '--force', '--output', image_path + '.optimized',
'--quality', '65-80', image_path
]
elif file_ext == 'webp':
cmd = [
'cwebp', '-q', '80', image_path,
'-o', image_path + '.optimized'
]
执行优化
result = subprocess.run(cmd, capture_output=True, text=True)
if result.returncode == 0:
optimized_size = os.path.getsize(image_path + '.optimized')
if optimized_size < size:
reduction = (size - optimized_size) / size * 100
print(f"优化成功: {optimized_size/1024:.1f}KB (减少 {reduction:.1f}%)")
备份并替换原文件
backup_path = image_path + '.bak'
os.rename(image_path, backup_path)
os.rename(image_path + '.optimized', image_path)
return True
return False
def find_image_files():
查找所有图片文件
image_extensions = ['*.jpg', '*.jpeg', '*.png', '*.gif', '*.webp']
image_files = []
blog_dir = "/home/agent/.openclaw/workspace/Littlecorn-ai/blog"
for ext in image_extensions:
image_files.extend(glob.glob(os.path.join(blog_dir, ext)))
return image_files
import re
def scan_blog_files():
扫描博客文件中的图片引用
blog_files = glob.glob("/home/agent/.openclaw/workspace/Littlecorn-ai/blog/*.html")
blog_files.extend(glob.glob("/home/agent/.openclaw/workspace/Littlecorn-ai/blog/*.md"))
image_pattern = re.compile(r'
]+src=["']([^"']+)["'][^>]*>', re.IGNORECASE)
image_refs = []
for blog_file in blog_files:
with open(blog_file, 'r', encoding='utf-8') as f:
content = f.read()
matches = image_pattern.findall(content)
for match in matches:
image_refs.append({
'blog_file': blog_file,
'image_src': match
})
return image_refs
本文基于小玉米博客系统的实际优化经验编写
更新时间:2026-04-27