86 lines
2.8 KiB
Python
86 lines
2.8 KiB
Python
|
|
"""
|
|||
|
|
小程序图片压缩脚本
|
|||
|
|
压缩 static 目录下的所有图片,减少主包体积
|
|||
|
|
"""
|
|||
|
|
from PIL import Image
|
|||
|
|
import os
|
|||
|
|
import sys
|
|||
|
|
|
|||
|
|
def compress_image(input_path, output_path, quality=60):
|
|||
|
|
"""压缩图片"""
|
|||
|
|
try:
|
|||
|
|
img = Image.open(input_path)
|
|||
|
|
|
|||
|
|
# 转换RGBA为RGB
|
|||
|
|
if img.mode == 'RGBA':
|
|||
|
|
background = Image.new('RGB', img.size, (255, 255, 255))
|
|||
|
|
background.paste(img, mask=img.split()[3])
|
|||
|
|
img = background
|
|||
|
|
elif img.mode != 'RGB':
|
|||
|
|
img = img.convert('RGB')
|
|||
|
|
|
|||
|
|
# 获取原始大小
|
|||
|
|
original_size = os.path.getsize(input_path) / 1024
|
|||
|
|
|
|||
|
|
# 压缩保存
|
|||
|
|
img.save(output_path, 'JPEG', quality=quality, optimize=True)
|
|||
|
|
|
|||
|
|
# 获取压缩后大小
|
|||
|
|
compressed_size = os.path.getsize(output_path) / 1024
|
|||
|
|
|
|||
|
|
print(f"✓ {os.path.basename(input_path)}: {original_size:.1f}KB -> {compressed_size:.1f}KB (减少 {((original_size-compressed_size)/original_size*100):.1f}%)")
|
|||
|
|
|
|||
|
|
return True
|
|||
|
|
except Exception as e:
|
|||
|
|
print(f"✗ 压缩失败 {input_path}: {str(e)}")
|
|||
|
|
return False
|
|||
|
|
|
|||
|
|
def main():
|
|||
|
|
static_dir = "peidu/uniapp/src/static"
|
|||
|
|
|
|||
|
|
# 需要压缩的目录
|
|||
|
|
dirs_to_compress = ['banner', 'button']
|
|||
|
|
|
|||
|
|
total_original = 0
|
|||
|
|
total_compressed = 0
|
|||
|
|
success_count = 0
|
|||
|
|
|
|||
|
|
print("=" * 60)
|
|||
|
|
print("开始压缩小程序图片...")
|
|||
|
|
print("=" * 60)
|
|||
|
|
|
|||
|
|
for dir_name in dirs_to_compress:
|
|||
|
|
dir_path = os.path.join(static_dir, dir_name)
|
|||
|
|
|
|||
|
|
if not os.path.exists(dir_path):
|
|||
|
|
print(f"⚠ 目录不存在: {dir_path}")
|
|||
|
|
continue
|
|||
|
|
|
|||
|
|
print(f"\n处理目录: {dir_name}/")
|
|||
|
|
print("-" * 60)
|
|||
|
|
|
|||
|
|
for filename in os.listdir(dir_path):
|
|||
|
|
if filename.lower().endswith(('.jpg', '.jpeg', '.png')):
|
|||
|
|
input_path = os.path.join(dir_path, filename)
|
|||
|
|
output_path = input_path
|
|||
|
|
|
|||
|
|
original_size = os.path.getsize(input_path) / 1024
|
|||
|
|
total_original += original_size
|
|||
|
|
|
|||
|
|
if compress_image(input_path, output_path, quality=60):
|
|||
|
|
compressed_size = os.path.getsize(output_path) / 1024
|
|||
|
|
total_compressed += compressed_size
|
|||
|
|
success_count += 1
|
|||
|
|
|
|||
|
|
print("\n" + "=" * 60)
|
|||
|
|
print("压缩完成!")
|
|||
|
|
print("=" * 60)
|
|||
|
|
print(f"成功压缩: {success_count} 个文件")
|
|||
|
|
print(f"原始总大小: {total_original:.1f}KB")
|
|||
|
|
print(f"压缩后总大小: {total_compressed:.1f}KB")
|
|||
|
|
print(f"节省空间: {total_original - total_compressed:.1f}KB ({((total_original-total_compressed)/total_original*100):.1f}%)")
|
|||
|
|
print("=" * 60)
|
|||
|
|
|
|||
|
|
if __name__ == "__main__":
|
|||
|
|
main()
|