project slimming #1
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| name: Optimize images to ~200KB | |
| on: | |
| push: | |
| branches: [ main ] | |
| paths: | |
| - '**/*.png' | |
| - '**/*.jpg' | |
| - '**/*.jpeg' | |
| jobs: | |
| optimize: | |
| runs-on: ubuntu-latest | |
| steps: | |
| - uses: actions/checkout@v4 | |
| - name: Setup Node | |
| uses: actions/setup-node@v4 | |
| with: | |
| node-version: '20' | |
| - name: Install squoosh CLI | |
| run: npm i -g @squoosh/cli | |
| - name: Convert & compress images toward <=200KB | |
| shell: bash | |
| run: | | |
| set -e | |
| # 需要处理的文件(排除已经是 webp 的) | |
| mapfile -t FILES < <(git ls-files | grep -Ei '\.(jpg|jpeg|png)$') | |
| # 如果没有新图,直接退出 | |
| if [ ${#FILES[@]} -eq 0 ]; then | |
| echo "No images to optimize." | |
| exit 0 | |
| fi | |
| # 目标上限(字节) | |
| TARGET=200000 | |
| # 最大宽度(超过就等比缩小;自行调整,如 1600/1920) | |
| MAXW=1920 | |
| for f in "${FILES[@]}"; do | |
| echo "Processing: $f" | |
| # 临时输出名(先转 webp) | |
| out="${f%.*}.webp" | |
| # 先做一次“温和”压缩与缩放 | |
| npx @squoosh/cli --webp auto --resize "max_width=${MAXW}" -d /tmp "$f" >/dev/null 2>&1 || true | |
| cand="/tmp/${out##*/}" | |
| # 如果仍超 200KB,则逐步降低质量重试 | |
| if [ -f "$cand" ]; then | |
| size=$(stat -c%s "$cand" 2>/dev/null || stat -f%z "$cand") | |
| else | |
| size=999999999 | |
| fi | |
| if [ "$size" -gt "$TARGET" ]; then | |
| for q in 85 80 75 70 65 60; do | |
| npx @squoosh/cli --webp "quality=${q}" --resize "max_width=${MAXW}" -d /tmp "$f" >/dev/null 2>&1 || true | |
| cand="/tmp/${out##*/}" | |
| size=$(stat -c%s "$cand" 2>/dev/null || stat -f%z "$cand") | |
| echo " Try quality=$q -> ${size} bytes" | |
| [ "$size" -le "$TARGET" ] && break | |
| done | |
| fi | |
| # 用 webp 替换原图(也可以选择另存到 assets/img/optimized/) | |
| if [ -f "$cand" ]; then | |
| mv "$cand" "$out" | |
| git rm -f --quiet "$f" | |
| git add "$out" | |
| echo " -> Saved as $out" | |
| fi | |
| done | |
| - name: Commit optimized images | |
| uses: EndBug/add-and-commit@v9 | |
| with: | |
| message: "chore: optimize images to ~200KB (webp, resize, quality step-down)" | |
| add: "." |