Files
homepage/tools/process_new_assets.py

51 lines
2.0 KiB
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

# -*- coding: utf-8 -*-
"""
处理用户补充的新素材(assets/img 内):
- 7 张透明底产品图 p-*:无损 WebP 保留 alpha(已是镂空,无需再处理)
- p-hs01 背景复杂不透明:有损压缩(页面走 framed 描边容器)
- 12 张照片 JPG:有损 WebP(宽度 >1600 的缩到 1600)
- qr-wechat.png 二维码:不处理,HTML 直接引用原 PNG
原图不删除(用户提供的源文件)。用法: uv run --with pillow python3 tools/process_new_assets.py
"""
from pathlib import Path
from PIL import Image
IMG = Path('assets/img')
# 已检测为真透明的产品图(透明像素 37%~88%)
ALPHA_PRODUCTS = [
'p-bb03.png', 'p-bg01.png', 'p-sg03.png', 'p-sg03mini.png',
'p-sl01.png', 'p-st01.png', 'p-st02.png',
]
# 有损压缩的照片/截图
PHOTOS = [
'p-hs01.png', # 背景复杂不透明,同照片处理
'ai-agent.jpg', 'app-livestock.jpg', 'building.jpg', 'cctv.jpg',
'digital-twin.jpg', 'factory-line.jpg', 'factory.jpg', 'goat.jpg',
'hero-grazing.jpg', 'hydro-class.jpg', 'liangchang.jpg',
'machine-install.jpg', 'platform-asset.jpg', 'platform-hydro.jpg',
'platform-pasture.jpg',
]
for name in ALPHA_PRODUCTS:
src = IMG / name
dst = IMG / (name[:-4] + '.webp')
im = Image.open(src).convert('RGBA')
# 自检:透明像素占比必须显著,否则说明误判为透明图
trans = sum(1 for p in im.getdata() if p[3] < 250) / (im.width * im.height)
assert trans > 0.2, f'{name} 透明像素仅 {trans:.0%},不符合透明底预期'
im.save(dst, 'WEBP', lossless=True, method=6)
print(f'{name:18s} -> {dst.name:22s} 透明{trans:.0%} {dst.stat().st_size // 1024}KB')
for name in PHOTOS:
src = IMG / name
dst = IMG / (name[:-4] + '.webp')
im = Image.open(src).convert('RGB')
if im.width > 1600:
im = im.resize((1600, round(im.height * 1600 / im.width)), Image.LANCZOS)
im.save(dst, 'WEBP', quality=82, method=6)
print(f'{name:18s} -> {dst.name:22s} {im.width}x{im.height} {dst.stat().st_size // 1024}KB')
print('完成')