/**
* 把 assets 里的 SVG 图标/头像栅格化成 PNG。
*
* 为什么需要:Lynx 在 Android 上走 Fresco 加载图片,而 Fresco 不认 SVG,
* logcat 里会看到 `LynxImageManager: onFailed ... reason: unknown image format`,
* 结果是所有 SVG 图标在真机/模拟器上都不显示(Web 端正常)。
*
* 做法:用无头 Edge 把这些 SVG 渲染成一张透明底的雪碧图,再按格子裁成单张 PNG。
*
* 用法: node scripts/rasterize-icons.mjs
*/
import { spawnSync } from 'node:child_process';
import fs from 'node:fs';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
const here = path.dirname(fileURLToPath(import.meta.url));
const repo = path.resolve(here, '..');
const ASSETS = path.join(repo, 'app', 'src', 'assets');
const CELL = 96; // 每个图标的栅格尺寸(原 viewBox 是 24,等于 4x)
const AVATAR_CELL = 192;
const COLS = 8;
/** 收集要处理的 svg */
function collect(dir, prefix) {
const full = path.join(ASSETS, dir);
if (!fs.existsSync(full)) return [];
return fs
.readdirSync(full)
.filter((f) => f.endsWith('.svg'))
.map((f) => ({
name: f.replace(/\.svg$/, ''),
outDir: `${prefix}`,
file: path.join(full, f),
content: fs.readFileSync(path.join(full, f), 'utf8'),
}));
}
const icons = collect('icons', 'icons-png');
const avatars = collect('avatars', 'avatars-png');
const groups = [
{ items: icons, cell: CELL, out: path.join(ASSETS, 'icons-png') },
{ items: avatars, cell: AVATAR_CELL, out: path.join(ASSETS, 'avatars-png') },
];
async function shoot(items, cell, outDir, tag) {
const rows = Math.ceil(items.length / COLS);
const width = COLS * cell;
const height = rows * cell;
const cells = items
.map(
(item) => `
${item.content
.replace(/width="\d+"/, `width="${cell}"`)
.replace(/height="\d+"/, `height="${cell}"`)}
`,
)
.join('\n');
const html = `${cells}
`;
const htmlPath = path.join(repo, `.rasterize-${tag}.html`);
fs.writeFileSync(htmlPath, html, 'utf8');
const pngPath = path.join(repo, `.rasterize-${tag}.png`);
fs.rmSync(pngPath, { force: true });
const res = spawnSync(
process.execPath,
[path.join(here, 'screenshot.mjs'), `file:///${htmlPath.replace(/\\/g, '/')}`, pngPath, '2500'],
{
stdio: 'inherit',
env: {
...process.env,
OMIT_BG: '1',
// 关键:视口必须正好是网格尺寸,否则网格会折行、裁剪就全错位
VIEWPORT: `${width}x${height}`,
SCALE: '1',
},
},
);
if (res.status !== 0) throw new Error('截图失败');
return { pngPath, htmlPath, width, height, rows };
}
const { execFileSync } = await import('node:child_process');
const PY = process.env.PYTHON || 'C:\\Users\\Administrator\\AppData\\Local\\Programs\\Python\\Python312\\python.exe';
for (const group of groups) {
if (group.items.length === 0) continue;
console.log(`\n=== ${group.out} :${group.items.length} 个 ===`);
const { pngPath, htmlPath } = await shoot(group.items, group.cell, group.out, path.basename(group.out));
fs.mkdirSync(group.out, { recursive: true });
// 用 Pillow 按格子裁
const cropScript = path.join(repo, `.rasterize-crop.py`);
fs.writeFileSync(
cropScript,
[
'import sys, json, os',
'from PIL import Image',
'src, out_dir, cell, cols, names = sys.argv[1], sys.argv[2], int(sys.argv[3]), int(sys.argv[4]), json.loads(sys.argv[5])',
'img = Image.open(src).convert("RGBA")',
'os.makedirs(out_dir, exist_ok=True)',
'for i, name in enumerate(names):',
' r, c = divmod(i, cols)',
' tile = img.crop((c * cell, r * cell, (c + 1) * cell, (r + 1) * cell))',
' tile.save(os.path.join(out_dir, name + ".png"))',
'print("cropped", len(names))',
].join('\n'),
'utf8',
);
const out = execFileSync(
PY,
[cropScript, pngPath, group.out, String(group.cell), String(COLS), JSON.stringify(group.items.map((i) => i.name))],
{ encoding: 'utf8' },
);
console.log(out.trim());
if (process.env.KEEP !== '1') {
fs.rmSync(htmlPath, { force: true });
fs.rmSync(pngPath, { force: true });
fs.rmSync(cropScript, { force: true });
} else {
console.log('保留了雪碧图:', pngPath);
}
}
console.log('\n完成,PNG 在 app/src/assets/icons-png 与 avatars-png');