feat(image-vectorize): v0.2 换 potrace 引擎,只做单色/灰度

用户裁定「只要单色/灰度就够」后重做:VTracer(彩色分层 wasm)换成 potrace
(纯 JS,Inkscape 同款内核)。文字笔画完整、turdSize 去掉毛刺、灰度层数 2–5。

- 纯 JS ⇒ 不需要宿主放宽 CSP;插件 238KB → 116KB
- 自带 potrace 移植(GPL-2.0,去 jimp 依赖,改吃 ImageData),License 随目录
- 灰度阈值自己按等像素量分位算(上游 steps:5 要 28s,这里几十 ms),
  并处理「主背景峰要排除」「切点必须严格递增」两个坑
- 新增 tools/trace-cli.mjs:拿真实素材直接跑参数、出对比图
- harness 重写 32 项(含「无 wasm-unsafe-eval 的 CSP 下跑通」反向锁);真站 e2e 13 项
This commit is contained in:
qiqi committed 2026-11-05 07:57:18 +08:00
1 parent 6f3a4676bb
commit c4e4b15375
29 files changed
+5949 -2321

No files matched your search

+37
View File
@@ -0,0 +1,37 @@
// 引擎单文件打包(开发用):把 plugin/engine.js + potrace 打成 IIFE 全局 VZEngine,便于在
// 浏览器里直接跑参数实验(tools/trace-cli.mjs 用它)。发布不走这里 —— 发布走根目录
// scripts/build-plugin.mjs(esbuild → 单文件 IIFE 插件)。
import path from 'node:path'
import { fileURLToPath } from 'node:url'
import { createRequire } from 'node:module'
const HERE = path.dirname(fileURLToPath(import.meta.url))
const PLUGIN = path.resolve(HERE, '../plugin')
const HOST_REPO = '/Users/qiqi/open/github/image-workbench-web'
const REPO = path.resolve(HERE, '../..')
export function esbuildModule() {
for (const base of [HOST_REPO, REPO, process.cwd()]) {
try {
return createRequire(path.join(base, 'package.json'))('esbuild')
} catch {
/* 试下一个 */
}
}
throw new Error('找不到 esbuild(宿主仓 node_modules 里应该有)')
}
export function bundleEngine(outfile = '/tmp/vz-engine.bundle.js') {
const esbuild = esbuildModule()
esbuild.buildSync({
entryPoints: [path.join(PLUGIN, 'engine.js')],
bundle: true,
format: 'iife',
globalName: 'VZEngine',
platform: 'browser',
target: ['chrome110'],
outfile,
logLevel: 'error',
})
return outfile
}
+9 -9
View File
@@ -1,8 +1,9 @@
// 真实站点端到端(开发用,不进 CI)。
//
// 与 harness 的分工:harness 用合成宿主,能验功能但不能验 CSP;这里走真站 ——
// 真实的 `_headers`(含 'wasm-unsafe-eval')、真实 KV、浏览器 SRI 校验、真实画布桥。
// 「wasm 能不能在宿主 CSP 下编译」只有这里能真验到。
// 与 harness 的分工:harness 用合成宿主,能验功能但不能验真实 CSP/网络;这里走真站 ——
// 真实的 `_headers`(**不含 wasm-unsafe-eval**)、真实 KV、浏览器 SRI 校验、真实画布桥。
// v0.2 是纯 JS potrace,所以这里反而要断言「wasm 仍被 CSP 拦住」——防止有人为了别的功能
// 悄悄把 'wasm-unsafe-eval' 加回去。
//
// 运行:
// node image-vectorize/tools/e2e-site.mjs
@@ -97,16 +98,15 @@ check('插件脚本用 SRI(sha256) 加载',
scripts.some((s) => s.src.indexOf('/plugins/plugin-' + PLUGIN_ID + '.') === 0 && /^sha256-/.test(s.integrity)),
JSON.stringify(scripts.map((s) => s.src)))
// ---------- 2) 宿主 CSP 放行 wasm(本插件存在的前提) ----------
// ---------- 2) 宿主 CSP 不再放行 wasm(v0.2 纯 JS,不需要放宽) ----------
const cspProbe = await page.evaluate(async () => {
try {
// (module) 最小 wasm,8 字节
const b = Uint8Array.from(atob('AGFzbQEAAAA='), (c) => c.charCodeAt(0))
await WebAssembly.instantiate(b)
return 'ok'
} catch (e) { return 'blocked: ' + e.message }
})
check('宿主 CSP 允许 wasm 编译(wasm-unsafe-eval)', cspProbe === 'ok', cspProbe.slice(0, 120))
check('宿主 CSP 仍禁止 wasm 编译(本插件是纯 JS,不该再放宽)', cspProbe.indexOf('blocked') === 0, cspProbe.slice(0, 120))
// ---------- 3) 打开工作区 ----------
await page.locator('.iwb-home-card:not(.iwb-home-new)').first().dblclick()
@@ -137,18 +137,18 @@ const paths = await poll(async () => {
const t = await page.locator('[data-stat="paths"]').textContent()
return t && t !== '–' && Number(t) > 0 ? t : false
}, 30000)
check('真站描摹成功(wasm 编译 + 执行)', Boolean(paths), 'paths=' + paths)
check('真站描摹成功(纯 JS 引擎,无 wasm)', Boolean(paths), 'paths=' + paths)
check('预览为 blob: SVG', await page.evaluate(() => {
const v = document.querySelector('[data-stage="vector"]')
return Boolean(v && /^blob:/.test(v.src) && !v.hidden)
}))
const stats = await page.evaluate(() => ({
colors: Number(document.querySelector('[data-stat="colors"]').textContent),
levels: Number(document.querySelector('[data-stat="levels"]').textContent),
bytes: document.querySelector('[data-stat="bytes"]').textContent,
ms: document.querySelector('[data-stat="ms"]').textContent,
}))
check('色层正常(≥3 色)', stats.colors >= 3, JSON.stringify(stats))
check('灰度层数正常(3 层)', stats.levels >= 3, JSON.stringify(stats))
// ---------- 6) 保存为节点(真实画布桥) ----------
await page.locator('[data-act="save"]').click()
+155 -103
View File
@@ -1,11 +1,11 @@
// 位图转矢量:本地端到端(开发用,不进 CI)。
// 位图转矢量(potrace 单色/灰度):本地端到端(开发用,不进 CI)。
//
// 直接把构建产物注入合成宿主,在真实 Chromium 里验证:
// 注册 / 模态 / wasm 引擎真跑出矢量 / 预设与参数联动 / 黑白模式禁用颜色项 /
// 颜色精度区间保护 / 边缘净化 / SVG 下载 / 保存为 PNG 节点 / 空格对比 / Esc 关闭 / 参数记忆。
// 注册 / 模态 / 单色描摹 / 灰度分层(层数联动)/ 参数联动 / 反相 / 去小点 / 颜色 /
// 下载 SVG / 保存为 PNG 节点 / 空格对比 / Esc 关闭 / 参数记忆。
//
// 页面刻意带上宿主同款 CSP(script-src 无 unsafe-inline,但有 wasm-unsafe-eval),
// 这样「wasm 能不能编译」这条约束是被真实测到的,而不是绕过去的。
// 页面刻意带上**与线上同款的 CSP**(`script-src 'self'`,没有 wasm-unsafe-eval):
// potrace 是纯 JS,这条断言顺带证明「本版不再需要放宽 CSP」。
//
// 运行:node image-vectorize/tools/harness.mjs
// 依赖:playwright(本仓/宿主仓 node_modules 均可;或用 IWB_PLAYWRIGHT_ROOT 指定)
@@ -35,17 +35,22 @@ const check = (name, ok, detail) => {
console.log((ok ? '✓ ' : '✗ ') + name + (detail ? ' ' + detail : ''))
}
const sleep = (ms) => new Promise((r) => setTimeout(r, ms))
// 描摹是异步的(wasm 一次几十毫秒 + 150ms 防抖),等统计数字出现即可
const waitStats = async (page, timeout = 8000) => {
const waitText = async (page, sel, timeout = 8000) => {
const end = Date.now() + timeout
for (;;) {
const t = await page.locator('[data-stat="paths"]').textContent().catch(() => null)
const t = await page.locator(sel).textContent().catch(() => null)
if (t && t !== '–') return t
if (Date.now() > end) return false
await sleep(120)
await sleep(100)
}
}
const pathsNow = (page) => page.locator('[data-stat="paths"]').textContent()
const levelsNow = (page) => page.locator('[data-stat="levels"]').textContent()
const svgNow = (page) => page.evaluate(() => {
const img = document.querySelector('[data-stage="vector"]')
if (!img || !img.src) return ''
return window.__lastSvg || ''
})
const browser = await chromium.launch()
const page = await browser.newPage({ viewport: { width: 1440, height: 1000 }, acceptDownloads: true })
@@ -54,20 +59,23 @@ page.on('console', (m) => { if (m.type() === 'error') errors.push(m.text()) })
page.on('pageerror', (e) => errors.push('pageerror: ' + e.message))
page.on('dialog', (d) => { errors.push('unexpected dialog: ' + d.message()); d.dismiss().catch(() => {}) })
const CSP = "default-src 'self'; script-src 'self' 'wasm-unsafe-eval'; style-src 'unsafe-inline'; img-src data: blob:; connect-src https: http:"
// 与线上 _headers 的 /* 组保持一致(**故意不带 wasm-unsafe-eval**)
const CSP = "default-src 'self'; script-src 'self'; style-src 'unsafe-inline'; img-src data: blob:; connect-src https: http:"
await page.setContent('<!doctype html><html><head><meta charset="utf-8"><meta http-equiv="Content-Security-Policy" content="' + CSP + '"><style>body{margin:0}</style></head><body><div id="host"></div></body></html>')
// 测试图:白底 + 红圆 + 蓝圆角矩形 + 黑色中文 + 绿色曲线(实心/圆角/文字/描边四类形态)
// 测试图:白底 + 红圆 + 蓝圆角矩形 + 黑色中文 + 绿色曲线(实心/圆角/文字/描边四类形态),
// 外加几个 1–2px 的孤立噪点(用来验证「去小点」真的吃掉它们)
const PNG = await page.evaluate(() => {
const c = document.createElement('canvas')
c.width = 400; c.height = 400
c.width = 480; c.height = 480
const g = c.getContext('2d')
g.fillStyle = '#ffffff'; g.fillRect(0, 0, 400, 400)
g.fillStyle = '#e8422f'; g.beginPath(); g.arc(120, 120, 74, 0, Math.PI * 2); g.fill()
g.fillStyle = '#1f5fa8'; g.beginPath(); g.roundRect(214, 164, 150, 104, 14); g.fill()
g.fillStyle = '#111111'; g.font = 'bold 46px "PingFang SC", sans-serif'; g.fillText('菜单', 124, 310)
g.strokeStyle = '#2e9e6b'; g.lineWidth = 4
g.beginPath(); g.moveTo(60, 356); g.bezierCurveTo(150, 330, 260, 390, 350, 350); g.stroke()
g.fillStyle = '#ffffff'; g.fillRect(0, 0, 480, 480)
g.fillStyle = '#e8422f'; g.beginPath(); g.arc(140, 140, 88, 0, Math.PI * 2); g.fill()
g.fillStyle = '#1f5fa8'; g.beginPath(); g.roundRect(252, 190, 176, 120, 16); g.fill()
g.fillStyle = '#111111'; g.font = 'bold 54px "PingFang SC", sans-serif'; g.fillText('菜单', 146, 372)
g.strokeStyle = '#2e9e6b'; g.lineWidth = 5
g.beginPath(); g.moveTo(70, 428); g.bezierCurveTo(176, 396, 306, 468, 412, 420); g.stroke()
for (const [x, y] of [[40, 40], [60, 44], [44, 62], [452, 60]]) g.fillRect(x, y, 2, 2)
return c.toDataURL('image/png')
})
@@ -77,10 +85,20 @@ await page.evaluate(() => {
window.__commands = {}
window.__settings = {}
window.__writes = []
// 抓每次产出的 SVG 原文:断言要能看内容(反相/颜色/层数),不能只数路径
window.__svgSeq = 0
window.__lastSvg = ''
const origCreate = URL.createObjectURL.bind(URL)
URL.createObjectURL = function (blob) {
const url = origCreate(blob)
if (blob && typeof blob.text === 'function' && String(blob.type || '').indexOf('image/svg') === 0) {
blob.text().then((t) => { window.__lastSvg = t; window.__svgSeq++ })
}
return url
}
})
// 产物用 CDP 直接执行注入:本页带 CSP(script-src 无 unsafe-inline),addScriptTag 会被拦。
// 这只影响「把代码装进页面」,插件运行时编译 wasm 仍受页面 CSP 约束 —— 那才是要测的点。
await page.evaluate(readFileSync(PLUGIN_ENTRY, 'utf8'))
const boot = await page.evaluate((png) => {
@@ -119,27 +137,30 @@ check('产物可执行(IIFE 打包 + 注册成功)', boot.version === WANT_V
check('注册了节点动作与命令', boot.actions.includes('vectorize-node') && boot.commands.includes('vectorize-selected'), boot.actions.join(','))
// 图标不能与别的插件撞车:'vector-square' 是 white-bg-800 的,两个插件同屏时认不出谁是谁(用户实测反馈过)
check('节点动作图标是钢笔笔头(不与 white-bg-800 的 vector-square 重复)', boot.icons.indexOf('pen-tool') >= 0 && boot.icons.indexOf('vector-square') < 0, boot.icons.join(','))
check('manifest 声明了参数记忆项', ['preset', 'colorPrecision', 'denoise', 'outScale'].every((k) => boot.settings.includes(k)), boot.settings.length + ' 项')
check('manifest 声明了参数记忆项', ['mode', 'levels', 'turdSize', 'alphaMax', 'invert', 'color', 'outScale'].every((k) => boot.settings.includes(k)), boot.settings.length + ' 项')
check('capabilities 含 canvasWrite(要写回节点)', boot.capabilities.includes('canvasWrite'), boot.capabilities.join(','))
await page.evaluate(() => { window.__commands['vectorize-selected'].run().catch(() => {}) })
// ---------- 打开模态 ----------
await page.evaluate(() => { window.__actions['vectorize-node'].run({ id: 'r1', type: 'ref', name: 'src.png' }) })
await page.locator('.vz-modal').waitFor({ state: 'visible', timeout: 15000 })
check('模态打开:预览区 + 参数面板 + 三个动作按钮齐全', await page.evaluate(() =>
Boolean(document.querySelector('.vz-preview') && document.querySelector('.vz-panel') &&
document.querySelector('[data-act="save"]') && document.querySelector('[data-act="svg"]') && document.querySelector('[data-act="cancel"]'))))
check('模态打开:预览区 + 参数面板 + 三个动作按钮齐全', await page.evaluate(() => {
const q = (s) => Boolean(document.querySelector(s))
return q('.vz-preview') && q('.vz-panel') && q('[data-act="cancel"]') && q('[data-act="svg"]') && q('[data-act="save"]')
const p0 = await waitText(page, '[data-stat="paths"]')
check('纯 JS 引擎在宿主 CSP 下跑通(无需 wasm-unsafe-eval)', Boolean(p0), 'paths=' + p0)
check('默认预设「文字 / 线稿」= 单色', await page.evaluate(() => {
const row = document.querySelector('[data-seg-group="mode"] button.active')
return Boolean(row && row.dataset.value === 'mono')
}))
const first = await waitStats(page)
check('wasm 引擎首次描摹成功(CSP 下 wasm 可编译)', Boolean(first) && Number(first) > 0, 'paths=' + first)
// ---------- 预览与棋盘 ----------
check('预览是矢量(blob: SVG 且不是原图)', await page.evaluate(() => {
const v = document.querySelector('[data-stage="vector"]')
const o = document.querySelector('[data-stage="original"]')
return Boolean(v && v.src.startsWith('blob:') && !v.hidden && o.hidden)
return Boolean(v && /^blob:/.test(v.src) && !v.hidden)
}))
// 透明区必须是中性灰棋盘:电商素材大量是黑字/深色 logo,深色棋盘会把内容直接吞掉,
// 看起来像「描摹失败」(这个坑实测踩过一次)
// 看起来像「描摹失败」(这个坑上一版实测踩过一次)
check('预览透明底用浅色棋盘(深色内容不会被吞)', await page.evaluate(() => {
const bg = getComputedStyle(document.querySelector('.vz-preview')).backgroundColor
const m = /rgba?\((\d+),\s*(\d+),\s*(\d+)/.exec(bg)
@@ -148,102 +169,133 @@ check('预览透明底用浅色棋盘(深色内容不会被吞)', await page
return lum > 150
}))
const stats = await page.evaluate(() => ({
paths: Number(document.querySelector('[data-stat="paths"]').textContent),
colors: Number(document.querySelector('[data-stat="colors"]').textContent),
bytes: document.querySelector('[data-stat="bytes"]').textContent,
ms: document.querySelector('[data-stat="ms"]').textContent,
}))
check('色层覆盖够用(红/蓝/黑/绿/白至少分 4 层)', stats.colors >= 4, JSON.stringify(stats))
check('描摹耗时 < 3s(400×400 参考图)', Number(String(stats.ms).replace('ms', '')) < 3000, stats.ms)
const monoPaths = Number(await pathsNow(page))
const monoMs = Number((await page.locator('[data-stat="ms"]').textContent()).replace(/[^\d]/g, ''))
check('单色描摹产出路径(文字图形都在)', monoPaths >= 1 && monoPaths <= 40, 'paths=' + monoPaths)
check('描摹耗时 < 1.5s(480×480)', monoMs > 0 && monoMs < 1500, monoMs + 'ms')
check('单色模式没有 fill-opacity(真单色,不是灰度伪装)', await page.evaluate(() => !/fill-opacity/.test(window.__lastSvg || '')), '')
check('默认预设为「标志 / 图标」且高亮', await page.evaluate(() => {
const a = document.querySelector('.vz-preset.active')
return Boolean(a && a.dataset.preset === 'logo')
// ---------- 灰度分层 ----------
await page.locator('[data-seg="mode"][data-value="gray"]').click()
await sleep(400)
const grayPaths = await waitText(page, '[data-stat="paths"]')
const grayLevels = await levelsNow(page)
check('切「灰度分层」:层数 = 3 且重新描摹', String(grayLevels) === '3' && Number(grayPaths) >= 3, 'paths=' + grayPaths + ' levels=' + grayLevels)
check('灰度层数行可见、单色颜色项禁用', await page.evaluate(() => {
const row = document.querySelector('[data-only="gray"]')
const color = document.querySelector('[data-color="color"]')
return Boolean(row && !row.hidden && color && color.disabled)
}))
await page.locator('.vz-preset[data-preset="photo"]').click()
await sleep(900)
check('切「照片」预设:颜色精度→4 且重新描摹', await page.evaluate(() =>
document.querySelector('[data-param="colorPrecision"]').value === '4' &&
document.querySelector('.vz-preset[data-preset="photo"]').classList.contains('active')),
'paths=' + await pathsNow(page))
await page.locator('[data-seg="levels"][data-value="5"]').click()
await sleep(500)
check('层数切到 5:层数统计跟着变(自定义阈值数组生效)', String(await levelsNow(page)) === '5', 'levels=' + await levelsNow(page))
await page.locator('[data-seg="levels"][data-value="3"]').click()
await sleep(400)
// 手动拖滑杆即脱离预设(预设只是参数组合的快捷方式)
// ---------- 去小点 ----------
const beforeTurd = await pathsNow(page)
await page.locator('[data-param="turdSize"]').fill('24')
await sleep(450)
const afterTurd = await waitText(page, '[data-stat="paths"]')
check('去小点调大后重新描摹(噪点应被吃掉,路径不增)', Number(afterTurd) <= Number(beforeTurd), beforeTurd + ' → ' + afterTurd)
await page.locator('[data-param="turdSize"]').fill('3')
await sleep(400)
// ---------- 边缘(alphaMax) ----------
const beforeTone = await page.evaluate(() => window.__svgSeq)
await page.locator('[data-seg="alphaTone"][data-value="round"]').click()
await sleep(450)
check('边缘「圆润」触发重新描摹(换了一套几何)', (await page.evaluate(() => window.__svgSeq)) > beforeTone)
await page.locator('[data-seg="alphaTone"][data-value="normal"]').click()
await sleep(400)
// ---------- 反相 ----------
const beforeInv = await page.evaluate(() => window.__svgSeq)
await page.locator('[data-act="adv"]').click()
await page.locator('[data-seg="invert"][data-value="1"]').click()
await sleep(450)
check('反相(负片)重新描摹', (await page.evaluate(() => window.__svgSeq)) > beforeInv)
await page.locator('[data-seg="invert"][data-value="0"]').click()
await sleep(400)
// ---------- 阈值手动 ----------
await page.locator('[data-seg="thrMode"][data-value="manual"]').click()
await sleep(150)
check('阈值切手动后滑杆出现', await page.evaluate(() => {
const row = document.querySelector('[data-thr-row]')
return Boolean(row && !row.hidden)
}))
await page.locator('[data-seg="thrMode"][data-value="auto"]').click()
await sleep(300)
// ---------- 颜色(单色) ----------
await page.locator('[data-seg="mode"][data-value="mono"]').click()
await sleep(400)
check('切回单色后颜色输入可用', await page.evaluate(() => {
const c = document.querySelector('[data-color="color"]')
return Boolean(c && !c.disabled)
}))
await page.evaluate(() => {
const i = document.querySelector('[data-param="filterSpeckle"]')
i.value = '20'
i.dispatchEvent(new Event('input', { bubbles: true }))
const c = document.querySelector('[data-color="color"]')
c.value = '#c0392b'
c.dispatchEvent(new Event('input', { bubbles: true }))
})
await sleep(700)
check('手动改参数后脱离预设高亮', await page.evaluate(() => !document.querySelector('.vz-preset.active')))
await sleep(400)
check('改单色填充色写进 SVG', await page.evaluate(() => /#c0392b/i.test(window.__lastSvg || '')), '')
await page.locator('[data-seg-group="binary"] button[data-value="binary"]').click()
await sleep(700)
check('黑白模式禁用颜色精度/色层差异(不假装可调)', await page.evaluate(() =>
document.querySelector('[data-param="colorPrecision"]').disabled &&
document.querySelector('[data-param="layerDifference"]').disabled))
check('黑白模式仍产出路径', await waitStats(page))
await page.locator('[data-seg-group="binary"] button[data-value="color"]').click()
await sleep(700)
check('切回彩色后颜色参数恢复可调', await page.evaluate(() => !document.querySelector('[data-param="colorPrecision"]').disabled))
// 实测:colorPrecision ≥6 会把整张图塌成一个色块,=8 直接 wasm abort,故滑杆必须夹在 1–5
check('颜色精度被夹在 1–5(引擎安全区间)', await page.evaluate(() => {
const i = document.querySelector('[data-param="colorPrecision"]')
return i.min === '1' && i.max === '5'
}))
await page.locator('[data-seg-group="denoise"] button[data-value="3"]').click()
await sleep(1100)
check('边缘净化 1/3:重新描摹并保持可用', Boolean(await waitStats(page)) &&
await page.evaluate(() => document.querySelector('[data-seg-group="denoise"] button.active')?.dataset.value === '3'),
'paths=' + await pathsNow(page))
const dlPromise = page.waitForEvent('download', { timeout: 12000 }).catch(() => null)
// ---------- 输出 ----------
const dl = page.waitForEvent('download', { timeout: 8000 })
await page.locator('[data-act="svg"]').click()
const download = await dlPromise
check('「下载 SVG」触发文件下载', Boolean(download) && /\.svg$/.test(download.suggestedFilename() || ''), download ? download.suggestedFilename() : 'no download')
const download = await dl
check('「下载 SVG」触发文件下载', /\.svg$/.test(download.suggestedFilename()), download.suggestedFilename())
await page.locator('[data-act="save"]').click()
await sleep(1400)
const wrote = await page.evaluate(() => window.__writes[0])
check('「保存为节点」写出 PNG 图片节点', Boolean(wrote) && wrote.kind === 'newNode' && wrote.head.startsWith('data:image/png'),
wrote ? JSON.stringify({ kind: wrote.kind, head: wrote.head, kb: Math.round(wrote.len / 1024) + 'KB' }) : 'no write')
await sleep(900)
check('「保存为节点」写出 PNG 图片节点', await page.evaluate(() =>
window.__writes.some((w) => w.kind === 'newNode' && /^data:image\/png;base64,/.test(w.head))),
JSON.stringify(await page.evaluate(() => window.__writes.slice(-1))))
check('保存后模态自动关闭', (await page.locator('.vz-root').count()) === 0)
check('参数记忆写回宿主 settings', await page.evaluate(() => {
const s = window.__settings
return Number(s.outScale) === 2 && Number(s.denoise) === 3 && s.binary === false && Number(s.filterSpeckle) === 20
}), await page.evaluate(() => JSON.stringify(window.__settings)))
// 重新打开应沿用上次参数
await page.evaluate(() => { window.__commands['vectorize-selected'].run().catch(() => {}) })
// ---------- 参数记忆 ----------
const mem = await page.evaluate(() => window.__settings)
check('参数记忆写回宿主 settings', mem && mem.mode === 'mono' && Number(mem.turdSize) === 3 && String(mem.color).toLowerCase() === '#c0392b', JSON.stringify(mem))
await page.evaluate(() => { window.__actions['vectorize-node'].run({ id: 'r1', type: 'ref', name: 'src.png' }) })
await page.locator('.vz-modal').waitFor({ state: 'visible', timeout: 15000 })
await waitStats(page)
check('重新打开沿用上次参数(filterSpeckle=20、denoise=1/3)', await page.evaluate(() =>
document.querySelector('[data-param="filterSpeckle"]').value === '20' &&
document.querySelector('[data-seg-group="denoise"] button.active')?.dataset.value === '3'))
check('重新打开沿用上次参数(mode=mono、颜色 #c0392b)', await page.evaluate(() => {
const active = document.querySelector('[data-seg-group="mode"] button.active')
const color = document.querySelector('[data-color="color"]')
return Boolean(active && active.dataset.value === 'mono' && color && color.value.toLowerCase() === '#c0392b')
}))
// 空格对比原图
// ---------- 空格对比 / Esc ----------
await page.evaluate(() => document.body.focus())
await page.keyboard.down('Space')
await sleep(220)
const spaceOn = await page.evaluate(() => !document.querySelector('[data-stage="original"]').hidden && document.querySelector('[data-badge]').textContent === '原图')
await sleep(150)
check('按住空格对比原图', await page.evaluate(() => {
const o = document.querySelector('[data-stage="original"]')
return Boolean(o && !o.hidden)
}))
await page.keyboard.up('Space')
await sleep(220)
const spaceOff = await page.evaluate(() => document.querySelector('[data-stage="original"]').hidden)
check('按住空格对比原图、松开回到矢量', spaceOn && spaceOff)
await sleep(120)
check('松开空格回到矢量', await page.evaluate(() => {
const o = document.querySelector('[data-stage="original"]')
const v = document.querySelector('[data-stage="vector"]')
return Boolean(o && o.hidden && v && !v.hidden)
}))
await page.keyboard.press('Escape')
await sleep(400)
await sleep(200)
check('Esc 关闭模态', (await page.locator('.vz-root').count()) === 0)
const fatal = errors.filter((e) => /Content Security Policy|Refused to|WebAssembly|is not defined|TypeError/i.test(e))
check('无 CSP / 运行时错误', fatal.length === 0, fatal.slice(0, 2).join(' | '))
if (errors.length) {
console.log('')
console.log('页面错误:')
for (const e of errors.slice(0, 6)) console.log(' ' + e)
console.log('控制台错误(' + errors.length + ' 条,前 5 条):')
for (const e of errors.slice(0, 5)) console.log(' ' + String(e).slice(0, 180))
}
console.log('')
console.log(failed ? '✗ 失败 ' + failed + ' 项' : '✓ 全部通过')
await browser.close()
+134
View File
@@ -0,0 +1,134 @@
// 单色/灰度描摹 CLI(开发用,不进 CI):把真实素材丢进去,直接看参数效果。
//
// node image-vectorize/tools/trace-cli.mjs <图片> [--mode mono|gray] [--levels 3]
// [--turd 3] [--alpha 1] [--invert] [--color #1a1a1a] [--threshold -1] [--out 目录]
//
// 产物:<out>/<name>-<mode><levels>.svg + 一张对比图 <out>/<name>-cmp.png(原图 / 结果 / 局部放大)。
// 为什么走浏览器:PNG/JPEG 解码和 ImageData 语义都与线上一致,Node 里没有等价的零依赖解码器。
import { createRequire } from 'node:module'
import fs from 'node:fs'
import path from 'node:path'
import { fileURLToPath } from 'node:url'
import { bundleEngine } from './bundle-engine.mjs'
const HERE = path.dirname(fileURLToPath(import.meta.url))
const REPO = path.resolve(HERE, '../..')
const HOST_REPO = '/Users/qiqi/open/github/image-workbench-web'
let chromium = null
for (const base of [HOST_REPO, REPO, process.cwd()]) {
try {
chromium = createRequire(path.join(base, 'package.json'))('playwright').chromium
break
} catch {
/* 试下一个 */
}
}
if (!chromium) {
console.error('✗ 找不到 playwright')
process.exit(2)
}
const argv = process.argv.slice(2)
const files = []
const opt = { mode: 'gray', levels: 3, turd: 3, alpha: 1, invert: false, color: '#1a1a1a', threshold: -1, out: '/tmp/vz-cli' }
for (let i = 0; i < argv.length; i++) {
const a = argv[i]
if (a === '--mode') opt.mode = argv[++i]
else if (a === '--levels') opt.levels = Number(argv[++i])
else if (a === '--turd') opt.turd = Number(argv[++i])
else if (a === '--alpha') opt.alpha = Number(argv[++i])
else if (a === '--invert') opt.invert = true
else if (a === '--color') opt.color = argv[++i]
else if (a === '--threshold') opt.threshold = Number(argv[++i])
else if (a === '--out') opt.out = argv[++i]
else if (a.startsWith('--')) throw new Error('未知参数 ' + a)
else files.push(a)
}
if (!files.length) {
console.error('用法:node image-vectorize/tools/trace-cli.mjs <图片...> [--mode mono|gray] [--levels 3] ...')
process.exit(2)
}
fs.mkdirSync(opt.out, { recursive: true })
const bundle = bundleEngine()
const bundleCode = fs.readFileSync(bundle, 'utf8')
const browser = await chromium.launch()
const page = await browser.newPage()
await page.setContent('<canvas id="c"></canvas>')
await page.addScriptTag({ content: bundleCode })
const params = {
mode: opt.mode,
levels: opt.levels,
turdSize: opt.turd,
alphaMax: opt.alpha,
invert: opt.invert,
color: opt.color,
threshold: opt.threshold,
outScale: 1,
}
for (const file of files) {
const b64 = fs.readFileSync(file).toString('base64')
const mime = /\.jpe?g$/i.test(file) ? 'image/jpeg' : 'image/png'
const res = await page.evaluate(
async ({ dataUrl, params }) => {
const img = new Image()
img.src = dataUrl
await img.decode()
const c = document.createElement('canvas')
c.width = img.naturalWidth
c.height = img.naturalHeight
const g = c.getContext('2d', { willReadFrequently: true })
g.drawImage(img, 0, 0)
const imageData = g.getImageData(0, 0, c.width, c.height)
const out = window.VZEngine.traceImageData(imageData, params)
return { svg: out.svg, ms: out.ms, paths: out.paths, levels: out.levels, w: c.width, h: c.height }
},
{ dataUrl: `data:${mime};base64,${b64}`, params }
)
const base = path.basename(file).replace(/\.[^.]+$/, '')
const tag = opt.mode === 'mono' ? 'mono' : 'gray' + res.levels
const svgPath = path.join(opt.out, `${base}-${tag}.svg`)
fs.writeFileSync(svgPath, res.svg)
console.log(
`${base} ${tag.padEnd(6)} ${String(res.paths).padStart(3)} paths ${String(res.ms).padStart(4)}ms ` +
`${(res.svg.length / 1024).toFixed(0)}KB ${res.w}×${res.h} → ${svgPath}`
)
// 对比图:原图 | 描摹结果
const cmp = await page.evaluate(
async ({ orig, svg, w, h }) => {
const load = (src) => new Promise((res, rej) => { const i = new Image(); i.onload = () => res(i); i.onerror = rej; i.src = src })
const a = await load(orig)
const b = await load('data:image/svg+xml;base64,' + btoa(unescape(encodeURIComponent(svg))))
const cw = 520
const ch = Math.round((h / w) * cw)
const cv = document.createElement('canvas')
cv.width = cw * 2 + 16
cv.height = ch + 24
const g = cv.getContext('2d')
g.fillStyle = '#fff'
g.fillRect(0, 0, cv.width, cv.height)
g.drawImage(a, 0, 20, cw, ch)
g.drawImage(b, cw + 16, 20, cw, ch)
g.fillStyle = '#333'
g.font = '12px system-ui'
g.fillText('原图', 4, 14)
g.fillText('描摹结果', cw + 20, 14)
return cv.toDataURL('image/png')
},
{
orig: `data:${mime};base64,${b64}`,
svg: res.svg.replace(/fill-opacity="0"/g, 'fill-opacity="0.001"'),
w: res.w,
h: res.h,
}
)
const cmpPath = path.join(opt.out, `${base}-cmp.png`)
fs.writeFileSync(cmpPath, Buffer.from(cmp.split(',')[1], 'base64'))
console.log(' 对比图 → ' + cmpPath)
}
await browser.close()