113 lines
3.4 KiB
Python
113 lines
3.4 KiB
Python
# -*- coding: utf-8 -*-
|
||
"""
|
||
压缩小程序图片
|
||
将 static 目录下的大图片压缩到合适大小
|
||
"""
|
||
import os
|
||
from PIL import Image
|
||
import sys
|
||
|
||
def compress_image(input_path, output_path, quality=85, max_width=1200):
|
||
"""
|
||
压缩图片
|
||
:param input_path: 输入图片路径
|
||
:param output_path: 输出图片路径
|
||
:param quality: 压缩质量 (1-100)
|
||
:param max_width: 最大宽度
|
||
"""
|
||
try:
|
||
# 打开图片
|
||
img = Image.open(input_path)
|
||
|
||
# 获取原始尺寸
|
||
width, height = img.size
|
||
original_size = os.path.getsize(input_path) / 1024 # KB
|
||
|
||
# 如果宽度超过最大宽度,按比例缩放
|
||
if width > max_width:
|
||
ratio = max_width / width
|
||
new_width = max_width
|
||
new_height = int(height * ratio)
|
||
img = img.resize((new_width, new_height), Image.Resampling.LANCZOS)
|
||
print(f" 缩放: {width}x{height} -> {new_width}x{new_height}")
|
||
|
||
# 转换为 RGB 模式(如果是 RGBA)
|
||
if img.mode in ('RGBA', 'LA', 'P'):
|
||
background = Image.new('RGB', img.size, (255, 255, 255))
|
||
if img.mode == 'P':
|
||
img = img.convert('RGBA')
|
||
background.paste(img, mask=img.split()[-1] if img.mode == 'RGBA' else None)
|
||
img = background
|
||
|
||
# 保存压缩后的图片
|
||
img.save(output_path, 'JPEG', quality=quality, optimize=True)
|
||
|
||
# 获取压缩后的大小
|
||
compressed_size = os.path.getsize(output_path) / 1024 # KB
|
||
ratio = (1 - compressed_size / original_size) * 100
|
||
|
||
print(f" 原始: {original_size:.2f}KB -> 压缩后: {compressed_size:.2f}KB (减少 {ratio:.1f}%)")
|
||
return True
|
||
|
||
except Exception as e:
|
||
print(f" 错误: {str(e)}")
|
||
return False
|
||
|
||
def main():
|
||
# 源目录和目标目录
|
||
source_dir = "peidu/uniapp/src/static/button"
|
||
|
||
# 需要压缩的大图片列表
|
||
large_images = [
|
||
"supervision.jpg",
|
||
"assessor.jpg",
|
||
"companion.jpg",
|
||
"study-tour.jpg",
|
||
"special.jpg",
|
||
"planner.jpg",
|
||
"summer-camp.jpg",
|
||
"interest.jpg",
|
||
"one-on-one.jpg",
|
||
"parent-academy.jpg"
|
||
]
|
||
|
||
print("开始压缩图片...")
|
||
print("=" * 60)
|
||
|
||
success_count = 0
|
||
fail_count = 0
|
||
|
||
for image_name in large_images:
|
||
input_path = os.path.join(source_dir, image_name)
|
||
|
||
if not os.path.exists(input_path):
|
||
print(f"\n跳过 {image_name} (文件不存在)")
|
||
continue
|
||
|
||
print(f"\n处理: {image_name}")
|
||
|
||
# 直接覆盖原文件
|
||
output_path = input_path
|
||
|
||
# 先保存到临时文件
|
||
temp_path = input_path + ".tmp"
|
||
|
||
if compress_image(input_path, temp_path, quality=85, max_width=1200):
|
||
# 删除原文件,重命名临时文件
|
||
os.remove(input_path)
|
||
os.rename(temp_path, output_path)
|
||
success_count += 1
|
||
else:
|
||
# 删除临时文件
|
||
if os.path.exists(temp_path):
|
||
os.remove(temp_path)
|
||
fail_count += 1
|
||
|
||
print("\n" + "=" * 60)
|
||
print(f"压缩完成!成功: {success_count}, 失败: {fail_count}")
|
||
print("\n请重新编译小程序:")
|
||
print(" npm run dev:mp-weixin")
|
||
|
||
if __name__ == "__main__":
|
||
main()
|