Files
iwb-plugins-desktop/image-vectorize/plugin/engine.js
T
qiqi d151de74a1 feat(image-vectorize): v0.2.1 精度可调 + 复制到剪贴板 + 高级默认展开
用户反馈三项:
1. 高级参数默认展开(不再藏起来),折叠按钮保留、展开状态记忆在 ctx.settings
2. 新增「复制 SVG」:一次写入 image/svg+xml + text/html + text/plain 三种口味,
   粘到 Figma / Illustrator 直接是真矢量。Chrome 对可写 MIME 有白名单,
   塞了不支持的类型会整次 write 失败,所以先 ClipboardItem.supports() 探测再逐级降级
3. 边缘精度可调:optTolerance 默认 0.2 → 0.05(三档 精细/标准/轻量),
   大图降采样上限 2000 → 3000px(实测单色 3200px 96ms、灰度 4 层 3000px 179ms)

预览底部的说明改为胶囊提示(原 #75758a 裸文字在浅灰棋盘上几乎看不见),
面板间距压紧,高级区展开后整列参数在 980px 高下不用滚。

验证:本地 harness 38 项、真站 e2e 17 项(含真实剪贴板读回校验)全绿。
2026-11-05 08:33:51 +08:00

188 lines
7.6 KiB
JavaScript
Raw 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.
/**
* 描摹引擎:potrace(纯 JS,GPL-2.0)—— 单色 / 灰度分层。
*
* 为什么换成 potrace(2026-11-05 用户裁定后的第二版):
* 上一版用 VTracer(彩色分层 + 样条拟合),文字图上会**断笔画、起毛刺、浅色块碎层**,
* 用户实测「看着变矢量但没法用」。potrace 是「二值轮廓追踪 + 曲线拟合」:
* 对 hard edge(文字、logo、线稿)的保形性明显更好,且 turdSize 天生能吃掉小毛刺。
* 代价是它只懂明暗(不懂颜色),所以只做**单色**与**灰度分层**——
* 用户明确说了「单色/灰度就够」,不再做彩色。
*
* 纯 JS ⇒ 不需要 wasm,**不需要宿主放宽 CSP**(上一版为此加过 'wasm-unsafe-eval',
* 下线时已收回;本版不要再动 CSP)。
*
* 灰度分层为什么自己算阈值:上游 Posterizer 的 `steps` 传数字时会走直方图多级阈值搜索,
* `steps: 5` 实测 28 秒(指数级),完全不可用。改为自己用**等像素量分位**算好阈值数组
* 直接传进去(O(pixels)),5 层也只要几十毫秒。
*/
'use strict'
import Potrace from './vendor/potrace/Potrace.js'
import Posterizer from './vendor/potrace/Posterizer.js'
export const MODES = ['gray', 'mono']
export const LEVELS_MIN = 2
export const LEVELS_MAX = 5
/**
* 描摹上限边(超过就降采样)。potrace 是纯 JS 单线程,实测:
* 单色 3200px 96ms、灰度 4 层 3000px 179ms(3600px 已跳到 389ms,内存压力明显)。
* 所以取 3000 —— 菜单/详情页这类大图的细节不再被降采样吃掉,同时仍在该帧内完成。
*/
export const MAX_TRACE_SIDE = 3000
export const DEFAULTS = {
mode: 'gray', // 'gray' 灰度分层 / 'mono' 纯单色
levels: 3, // 灰度层数(2–5,仅 gray)
threshold: -1, // -1 = 自动(两种模式都支持)
turdSize: 3, // 去小点:面积小于它的碎片直接丢(毛刺/噪点克星)
alphaMax: 1, // 拐角阈值:0 全折线、1 默认、1.334 最圆
// 曲线拟合容差(越小越贴合原图像素边缘,路径数据也越大)。
// 上游默认 0.2 是「视觉上够用」的省数据值;实测 0.2 在文字笔画与圆角处会
// 吃掉约半个像素的弯折,所以这里默认降到 0.05(用户 2026-11-05 要求「边缘精度再高一点」)。
optTolerance: 0.05,
invert: false, // 反相:描摹亮部(黑底白字场景)
color: '#1a1a1a', // mono 的填充色
outScale: 1, // 输出尺寸倍率(只放大尺寸,不重算曲线)
}
/** 曲线精度三档(UI 用):越大越省路径数据,越小越贴合像素 */
export const TOLERANCE_TONES = { fine: 0.05, normal: 0.15, light: 0.4 }
const clampInt = (v, min, max, dflt) => {
const n = Math.round(Number(v))
return Number.isFinite(n) ? Math.min(max, Math.max(min, n)) : dflt
}
/** 把 UI / 记忆里的松散参数收敛成引擎能吃的确定值 */
export function normalizeParams(p) {
const src = p || {}
return {
mode: src.mode === 'mono' ? 'mono' : 'gray',
levels: clampInt(src.levels, LEVELS_MIN, LEVELS_MAX, DEFAULTS.levels),
threshold: Number(src.threshold) >= 0 ? clampInt(src.threshold, 0, 255, 128) : -1,
turdSize: clampInt(src.turdSize, 0, 64, DEFAULTS.turdSize),
alphaMax: (() => {
const n = Number(src.alphaMax)
return Number.isFinite(n) ? Math.min(1.334, Math.max(0, n)) : DEFAULTS.alphaMax
})(),
optTolerance: (() => {
const n = Number(src.optTolerance)
return Number.isFinite(n) ? Math.min(2, Math.max(0.01, n)) : DEFAULTS.optTolerance
})(),
invert: Boolean(src.invert),
color: /^#[0-9a-f]{6}$/i.test(String(src.color || '')) ? String(src.color) : DEFAULTS.color,
outScale: Math.min(4, Math.max(1, Number(src.outScale) || 1)),
}
}
/**
* 等像素量分位阈值:把亮度直方图按像素数切成 levels 段,返回 levels-1 个切点。
*
* 两个必须处理的坑(实测,不是理论问题):
* 1. **主背景色要排除在人口统计之外**。电商图/菜单图里底色常占 60–80% 像素,
* 不排除的话三个切点里有两个会落在背景里,文字还是跟背景分不开(等于没分层)。
* 2. **切点必须严格递增**。背景是一个巨大的尖峰,多个切点会算出同一个亮度值,
* 去重后层数变少(Posterizer 还会算出 0 透明度,整层消失)。
*/
function quantileThresholds(imageData, levels) {
const hist = new Uint32Array(256)
const data = imageData.data
let total = 0
for (let i = 0; i < data.length; i += 4) {
const a = data[i + 3] / 255
// 与 potrace 内部一致:透明按白底合成后再算亮度
const r = 255 + (data[i] - 255) * a
const g = 255 + (data[i + 1] - 255) * a
const b = 255 + (data[i + 2] - 255) * a
hist[Math.round(0.299 * r + 0.587 * g + 0.114 * b)]++
total++
}
if (!total) return []
// 1) 排除主背景峰(最常见的那个亮度)
let bg = 0
let bgCount = 0
for (let v = 0; v < 256; v++) if (hist[v] > bgCount) { bgCount = hist[v]; bg = v }
const counted = total - bgCount
// 内容太少(几乎纯色图)就退化成等间距,别硬分层
if (counted < total * 0.02) {
const out = []
for (let k = 1; k < levels; k++) out.push(Math.round((255 * k) / levels))
return out
}
// 2) 在「非背景」像素上取等量分位(背景 bin 当 0 处理,但仍参与 value 轴)
const saved = hist[bg]
hist[bg] = 0
const cuts = []
const per = counted / levels
let acc = 0
let next = per
for (let v = 0; v < 256 && cuts.length < levels - 1; v++) {
acc += hist[v]
while (acc >= next && cuts.length < levels - 1) {
cuts.push(v)
next += per
}
}
hist[bg] = saved
// 3) 强制严格递增 + 留出余量(相邻层差至少 1 个亮度级)
const out = []
for (const c of cuts) {
let v = c
if (out.length && v <= out[out.length - 1]) v = out[out.length - 1] + 1
if (v > 254) break
out.push(v)
}
return out
}
/**
* 描摹主入口(同步)。
* @param {{width:number,height:number,data:Uint8ClampedArray}} imageData
* @param {object} params
* @returns {{svg:string, ms:number, paths:number, levels:number}}
*/
export function traceImageData(imageData, params) {
const p = normalizeParams(params)
const now = () => (typeof performance !== 'undefined' ? performance.now() : Date.now())
const t0 = now()
let svg = ''
let levels = 1
if (p.mode === 'mono') {
const potrace = new Potrace({
threshold: p.threshold >= 0 ? p.threshold : Potrace.THRESHOLD_AUTO,
turdSize: p.turdSize,
alphaMax: p.alphaMax,
optCurve: true,
optTolerance: p.optTolerance,
blackOnWhite: !p.invert,
color: p.color,
})
potrace.loadImageData(imageData)
svg = potrace.getSVG()
} else {
const cuts = quantileThresholds(imageData, p.levels)
levels = cuts.length + 1
const posterizer = new Posterizer({
// 传数组 ⇒ 跳过上游的直方图多级阈值搜索(那玩意 5 层要 28s)
steps: cuts.length ? cuts : [128],
threshold: p.threshold >= 0 ? p.threshold : Potrace.THRESHOLD_AUTO,
turdSize: p.turdSize,
alphaMax: p.alphaMax,
optCurve: true,
optTolerance: p.optTolerance,
blackOnWhite: !p.invert,
fillStrategy: 'median', // 灰度:每层取该层亮度中位数
color: '#000000', // 灰度靠 fill-opacity 叠出来,底色固定黑
})
posterizer.loadImageData(imageData)
svg = posterizer.getSVG()
}
return { svg, ms: Math.round(now() - t0), paths: (String(svg).match(/<path/g) || []).length, levels }
}