From c4e4b153758e085cbaf2a35ba7e03de235ac1336 Mon Sep 17 00:00:00 2001 From: qiqi Date: Thu, 5 Nov 2026 07:57:18 +0800 Subject: [PATCH] =?UTF-8?q?feat(image-vectorize):=20v0.2=20=E6=8D=A2=20pot?= =?UTF-8?q?race=20=E5=BC=95=E6=93=8E=EF=BC=8C=E5=8F=AA=E5=81=9A=E5=8D=95?= =?UTF-8?q?=E8=89=B2/=E7=81=B0=E5=BA=A6?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 用户裁定「只要单色/灰度就够」后重做: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 项 --- image-annotate/docs/PS_LITE_ROADMAP.md | 213 +- image-vectorize/README.md | 97 +- image-vectorize/package.json | 4 +- image-vectorize/plugin/engine.js | 234 +- image-vectorize/plugin/manifest.banner.js | 20 +- image-vectorize/plugin/trace.js | 263 +- image-vectorize/plugin/ui.css | 21 + image-vectorize/plugin/ui.js | 301 +- .../plugin/vendor/VTracer-LICENSE.txt | 21 - image-vectorize/plugin/vendor/potrace/LICENSE | 339 ++ .../plugin/vendor/potrace/Posterizer.js | 458 +++ .../plugin/vendor/potrace/Potrace.js | 1169 ++++++ .../plugin/vendor/potrace/types/Bitmap.js | 111 + .../plugin/vendor/potrace/types/Curve.js | 21 + .../plugin/vendor/potrace/types/Histogram.js | 425 +++ .../plugin/vendor/potrace/types/Opti.js | 13 + .../plugin/vendor/potrace/types/Path.js | 14 + .../plugin/vendor/potrace/types/Point.js | 14 + .../plugin/vendor/potrace/types/Quad.js | 11 + .../plugin/vendor/potrace/types/Sum.js | 11 + .../plugin/vendor/potrace/utils.js | 253 ++ image-vectorize/plugin/vendor/vtracer.js | 452 --- image-vectorize/plugin/vendor/vtracer.wasm | Bin 136862 -> 0 bytes image-vectorize/plugin/vendor/wasm-b64.js | 4 - image-vectorize/src/index.js | 3354 +++++++++++------ image-vectorize/tools/bundle-engine.mjs | 37 + image-vectorize/tools/e2e-site.mjs | 18 +- image-vectorize/tools/harness.mjs | 258 +- image-vectorize/tools/trace-cli.mjs | 134 + 29 files changed, 5949 insertions(+), 2321 deletions(-) delete mode 100644 image-vectorize/plugin/vendor/VTracer-LICENSE.txt create mode 100644 image-vectorize/plugin/vendor/potrace/LICENSE create mode 100644 image-vectorize/plugin/vendor/potrace/Posterizer.js create mode 100644 image-vectorize/plugin/vendor/potrace/Potrace.js create mode 100644 image-vectorize/plugin/vendor/potrace/types/Bitmap.js create mode 100644 image-vectorize/plugin/vendor/potrace/types/Curve.js create mode 100644 image-vectorize/plugin/vendor/potrace/types/Histogram.js create mode 100644 image-vectorize/plugin/vendor/potrace/types/Opti.js create mode 100644 image-vectorize/plugin/vendor/potrace/types/Path.js create mode 100644 image-vectorize/plugin/vendor/potrace/types/Point.js create mode 100644 image-vectorize/plugin/vendor/potrace/types/Quad.js create mode 100644 image-vectorize/plugin/vendor/potrace/types/Sum.js create mode 100644 image-vectorize/plugin/vendor/potrace/utils.js delete mode 100644 image-vectorize/plugin/vendor/vtracer.js delete mode 100644 image-vectorize/plugin/vendor/vtracer.wasm delete mode 100644 image-vectorize/plugin/vendor/wasm-b64.js create mode 100644 image-vectorize/tools/bundle-engine.mjs create mode 100644 image-vectorize/tools/trace-cli.mjs diff --git a/image-annotate/docs/PS_LITE_ROADMAP.md b/image-annotate/docs/PS_LITE_ROADMAP.md index 4b8f5b3..d850bf6 100644 --- a/image-annotate/docs/PS_LITE_ROADMAP.md +++ b/image-annotate/docs/PS_LITE_ROADMAP.md @@ -1,9 +1,9 @@ # 简化版 PS(Image Editor Lite)目标与实施分析 -> 基线:`image-annotate` v1.0.5(`plugin-image-annotate.cfecb6e2ec17.js`),宿主 `image-workbench-web` 插件 API v1。 +> 基线:`image-annotate` v1.0.5(`plugin-image-annotate.cfecb6e2ec17.js`),宿主 `image-workbench-web` 插件 API v1。 > 本文只做目标定义、差距分析、UI/架构/分期设计,**不含代码改动**。改动前先确认文末「待拍板」一节。 > -> **范围裁定(用户确认)**:只做**单张图片**的编辑与输出,**不做批量出图 / 多图队列 / 批量导出**; +> **范围裁定(用户确认)**:只做**单张图片**的编辑与输出,**不做批量出图 / 多图队列 / 批量导出**; > UI 以「**便利 / 顺手**」为第一目标,不以「像 PS」为目标 —— 菜单层级、弹窗、确认步骤能省则省。 > > **决策裁定(2026-11-04)**:① 选区 `Delete` **只作用当前图层**;②「清空标注」=**全部还原到打开时的原图**(删掉所有非原图图层 + 清掉所有绘制/变换,且可撤销);③ **≤500KB 做成输出预设**(不默认产两个文件);④ **浮动操作条先实现、上线后由用户实际体验再裁定**保留/调整/移除,本轮不因「待体验」而停工。详见 §8。 @@ -14,14 +14,14 @@ 现在的插件是一个**功能很强的标注器**,但还不是一个**图像编辑器**。差距不在「工具数量少」(已有 11 个工具),而在三根缺失的柱子: -| 柱子 | 现状 | 对齐目标后 | -| --- | --- | --- | -| 选区 | 只有裁剪框(`S.cropRect`)和钢笔路径,没有「可作用于像素的选区」 | 框选 → 复制/剪切到新层 / 清除 / 填充 / 限制画笔 | -| 非破坏性 | `confirmCrop()` 把所有可见层 flatten 成一张图,并清空撤销栈 | 裁剪、变换、图层结构都可撤销;导出时才合成 | -| 输出工作流 | 只有 PNG Blob → 覆盖/新建节点 | 单张:格式、尺寸、背景、体积上限、下载/剪贴板可配置 | +| 柱子 | 现状 | 对齐目标后 | +| ----- | ------------------------------------------ | ------------------------------ | +| 选区 | 只有裁剪框(`S.cropRect`)和钢笔路径,没有「可作用于像素的选区」 | 框选 → 复制/剪切到新层 / 清除 / 填充 / 限制画笔 | +| 非破坏性 | `confirmCrop()` 把所有可见层 flatten 成一张图,并清空撤销栈 | 裁剪、变换、图层结构都可撤销;导出时才合成 | +| 输出工作流 | 只有 PNG Blob → 覆盖/新建节点 | 单张:格式、尺寸、背景、体积上限、下载/剪贴板可配置 | -建议路径:**先重做地基与 UI(P0)→ 上选区(P1)→ 修裁剪/画布(P2)→ 图层增强(P3)→ 输出工作流(P4)**。 -不要直接往现有 `events.js` 里堆选区分支:它已经 1416 行,`editor.css` 1340 行且后半段是补丁叠加,继续堆会很快失控。 +建议路径:**先重做地基与 UI(P0)→ 上选区(P1)→ 修裁剪/画布(P2)→ 图层增强(P3)→ 输出工作流(P4)**。 +不要直接往现有 `events.js` 里堆选区分支:它已经 1416 行,`e `40 行且后半段是补丁叠加,继续堆会很快失控。 > 便利性不改变架构判断,反而强化了 P0 的必要性:高频动作要「就地、一步可达」,靠的是命令层与统一状态机,而不是往菜单里加更多条目。 @@ -37,56 +37,56 @@ 打开图片 → 框选/抠出局部 → 图层化编辑 → 裁剪 / 改尺寸 → 按规范导出 → 回写节点 ``` -典型场景:截图里圈出商品 → 复制成独立层 → 擦掉多余部分 → 裁成 800×800 → 导出当前这一张。 +典型场景:截图里圈出商品 → 复制成独立层 → 擦掉多余部分 → 裁成 800×800 → 导出当前这一张。 **一次会话只处理一张图,输出一次只产出一个结果**;不引入队列、批量选择、批量命名、批量下载等概念。 ### 1.2 明确不做(边界) -| 不做 | 原因 | -| --- | --- | -| **批量出图 / 多图队列 / 批量导出 / 批量改名** | 用户明确排除;单张处理即可,避免把编辑器做成队列面板 | -| 调色:曲线 / 色阶 / HSL / 色彩平衡 / 色相饱和度 | 用户明确排除;牵涉色彩管理与 LUT,收益低 | -| 滤镜 / 模糊 / 锐化 / 降噪(作为调色类功能) | 同上;**羽化**作为选区属性保留 | -| CMYK / 16bit / RAW / ICC / 印刷输出 | 浏览器 Canvas 2D 只有 8bit sRGB | -| 智能对象 / 动作 / 脚本 / 通道 / 路径面板 | 复杂度远超「简化版」 | -| AI 抠图 | 已有外部链路(`xianyi-cutout` / 本地 rembg),插件只负责后期修图 | -| 非破坏性蒙版式调色图层 | 一期不需要;P3 只做「图层蒙版」这一项 | -| 完整菜单栏(文件/编辑/图像/图层/选择/视图…) | 与「便利」冲突;低频命令收进一个「更多」下拉 | +| 不做 | 原因 | +| ------------------------------- | -------------------------------------------- | +| **批量出图 / 多图队列 / 批量导出 / 批量改名** | 用户明确排除;单张处理即可,避免把编辑器做成队列面板 | +| 调色:曲线 / 色阶 / HSL / 色彩平衡 / 色相饱和度 | 用户明确排除;牵涉色彩管理与 LUT,收益低 | +| 滤镜 / 模糊 / 锐化 / 降噪(作为调色类功能) | 同上;**羽化**作为选区属性保留 | +| CMYK / 16bit / RAW / ICC / 印刷输出 | 浏览器 Canvas 2D 只有 8bit sRGB | +| 智能对象 / 动作 / 脚本 / 通道 / 路径面板 | 复杂度远超「简化版」 | +| AI 抠图 | 已有外部链路(`xianyi-cutout` / 本地 rembg),插件只负责后期修图 | +| 非破坏性蒙版式调色图层 | 一期不需要;P3 只做「图层蒙版」这一项 | +| 完整菜单栏(文件/编辑/图像/图层/选择/视图…) | 与「便利」冲突;低频命令收进一个「更多」下拉 | ### 1.3 与 PS 的能力对照 -| PS 能力 | 简化版取舍 | -| --- | --- | -| 选框 / 套索 / 魔棒 | ✅ 矩形、椭圆、多边形、自由套索;魔棒放二期 | -| 选区变换 / 加减 / 反选 / 羽化 | ✅ 一期全做(羽化用 Canvas filter) | -| 复制 / 剪切到新图层、清除、填充、描边 | ✅ 核心,且做成选区旁的浮动操作条 | -| 图层 / 显隐 / 锁定 / 不透明度 / 排序 | ✅ 已有 | -| 混合模式 / 图层蒙版 / 编组 / 缩略图 | 🟡 P3 补 | -| 裁剪 / 画布大小 / 图像大小 / 旋转翻转 | 🟡 P2 补,且改为可撤销 | -| 自由变换(Ctrl+T) | 🟡 已有选中对象的移动/缩放/旋转,P2 扩展到选区内容 | -| 画笔 / 橡皮 / 文字 / 形状 / 吸管 / 抓手 | ✅ 已有,不重写 | -| 历史面板 / 多步撤销 | ✅ 已有栈,P0 补标签与面板 | -| 导出 / 存储为 Web 所用格式 | 🟡 P4,单张可配置预设 | -| 菜单栏 / 批量处理 / 滤镜 / 调色 / 3D / 印刷 | ❌ 不做 | +| PS 能力 | 简化版取舍 | +| ------------------------------ | ----------------------------- | +| 选框 / 套索 / 魔棒 | ✅ 矩形、椭圆、多边形、自由套索;魔棒放二期 | +| 选区变换 / 加减 / 反选 / 羽化 | ✅ 一期全做(羽化用 Canvas filter) | +| 复制 / 剪切到新图层、清除、填充、描边 | ✅ 核心,且做成选区旁的浮动操作条 | +| 图层 / 显隐 / 锁定 / 不透明度 / 排序 | ✅ 已有 | +| 混合模式 / 图层蒙版 / 编组 / 缩略图 | 🟡 P3 补 | +| 裁剪 / 画布大小 / 图像大小 / 旋转翻转 | 🟡 P2 补,且改为可撤销 | +| 自由变换(Ctrl+T) | 🟡 已有选中对象的移动/缩放/旋转,P2 扩展到选区内容 | +| 画笔 / 橡皮 / 文字 / 形状 / 吸管 / 抓手 | ✅ 已有,不重写 | +| 历史面板 / 多步撤销 | ✅ 已有栈,P0 补标签与面板 | +| 导出 / 存储为 Web 所用格式 | 🟡 P4,单张可配置预设 | +| 菜单栏 / 批量处理 / 滤镜 / 调色 / 3D / 印刷 | ❌ 不做 | --- ## 2. 现状盘点(代码级) -| 能力 | 实现位置 | 关键事实 | -| --- | --- | --- | -| 11 个工具 | `editor/dom.js` 工具栏 + `editor/events.js` 分发 | select / brush / eraser / pen / text / rect / circle / arrow / picker / hand / crop | -| 位图图层 | `editor/viewport.js#setupCanvas` | 初始 `base`(locked, z=0) + `draw`(z=1);**每个图层都是 imgW×imgH 全幅 canvas** | -| 矢量对象 | `editor/objects.js` `layerUnits()` | 文字/形状/钢笔按 z 与位图混排,1.0.5 已统一为唯一真源 | -| 图层面板 | `editor/layers.js#renderLayerPanel` | 显隐 / 锁定 / 删除 / 颜色 / 线宽 / 透明度 / 拖拽排序 / 4 个排序按钮;**无缩略图、无混合模式、无编组、无多选** | -| 历史 | `editor/history.js` | `snapshotState()` 像素快照;50 条 + 32–128MB 双预算;`restorePath()` 决定哪些层跳过像素 | -| 裁剪 | `editor/crop.js#confirmCrop` | `getCompositeCanvas()` → flatten → `setupCanvas(cropC)` 重建所有层 → 改 `S.imgW/imgH` → **`S.history=[]`**;比例/尺寸约束;越界部分透明 | -| 图片放置 | `editor/placement.js` | 粘贴/导入先进入放置模式(移动/8 手柄/旋转),**必须 Enter 或点击外部确认才落层** | -| 剪贴板 | `editor/events.js#onPaste` | document 捕获阶段,命中图片即 `stopImmediatePropagation()`(防宿主 window 抢粘贴) | -| 视图 | `editor/viewport.js` | zoom 0.1–10、自由平移、`overlayPad` 交互外扩、`getPos()` 统一坐标换算 | -| 输出 | `editor/index.js#exportResult` | 固定 PNG `toBlob` → `glue.js` 转 dataURL → `setNodeImage` / `createImageNode` | -| 内存 | `editor/index.js#releaseEditorMemory` | `close()` 释放所有像素、原图、历史;**会话状态不保留** | -| 宿主 | `plugin/glue.js` | 只对 `ref` 节点暴露;`ctx.canvas.*`;`ctx.storage` 是宿主提供的小 KV(localStorage),**不是像素仓库** | +| 能力 | 实现位置 | 关键事实 | +| ------ | ------------------------------------------- | ------------------------------------------------------------------------------------------------------------------- | +| 11 个工具 | `editor/dom.js` 工具栏 + `editor/events.js` 分发 | select / brush / eraser / pen / text / rect / circle / arrow / picker / hand / crop | +| 位图图层 | `editor/viewport.js#setupCanvas` | 初始 `base`(locked, z=0) + `draw`(z=1);**每个图层都是 imgW×imgH 全幅 canvas** | +| 矢量对象 | `editor/objects.js` `layerUnits()` | 文字/形状/钢笔按 z 与位图混排,1.0.5 已统一为唯一真源 | +| 图层面板 | `editor/layers.js#renderLayerPanel` | 显隐 / 锁定 / 删除 / 颜色 / 线宽 / 透明度 / 拖拽排序 / 4 个排序按钮;**无缩略图、无混合模式、无编组、无多选** | +| 历史 | `editor/history.js` | `snapshotState()` 像素快照;50 条 + 32–128MB 双预算;`restorePath()` 决定哪些层跳过像素 | +| 裁剪 | `editor/crop.js#confirmCrop` | `getCompositeCanvas()` → flatten → `setupCanvas(cropC)` 重建所有层 → 改 `S.imgW/imgH` → **`S.history=[]`**;比例/尺寸约束;越界部分透明 | +| 图片放置 | `editor/placement.js` | 粘贴/导入先进入放置模式(移动/8 手柄/旋转),**必须 Enter 或点击外部确认才落层** | +| 剪贴板 | `editor/events.js#onPaste` | document 捕获阶段,命中图片即 `stopImmediatePropagation()`(防宿主 window 抢粘贴) | +| 视图 | `editor/viewport.js` | zoom 0.1–10、自由平移、`overlayPad` 交互外扩、`getPos()` 统一坐标换算 | +| 输出 | `editor/index.js#exportResult` | 固定 PNG `toBlob` → `glue.js` 转 dataURL → `setNodeImage` / `createImageNode` | +| 内存 | `editor/index.js#releaseEditorMemory` | `close()` 释放所有像素、原图、历史;**会话状态不保留** | +| 宿主 | `plugin/glue.js` | 只对 `ref` 节点暴露;`ctx.canvas.*`;`ctx.storage` 是宿主提供的小 KV(localStorage),**不是像素仓库** | --- @@ -96,61 +96,61 @@ ### 3.1 选区(当前完全没有) -| 缺口 | 影响 | 优先级 | -| --- | --- | --- | -| 无矩形/椭圆/多边形/套索选区 | 无法「抠出局部」「只擦一块」 | P1 | -| 无蚂蚁线、无加减选、无反选/全选/取消 | 选区不可见、不可调整 | P1 | -| 无羽化 | 边缘生硬,合成痕迹明显 | P1 | -| 无复制/剪切到新层、Delete 清除、填充/描边 | 选区没有落点,等于没用 | P1 | -| 选区不能约束画笔/橡皮 | 精细化修图做不到 | P1(可后置) | -| 魔棒 / 色彩范围 | 纯色背景一键去背 | P2+(worker 受限,见 §7) | +| 缺口 | 影响 | 优先级 | +| ------------------------- | -------------- | ------------------- | +| 无矩形/椭圆/多边形/套索选区 | 无法「抠出局部」「只擦一块」 | P1 | +| 无蚂蚁线、无加减选、无反选/全选/取消 | 选区不可见、不可调整 | P1 | +| 无羽化 | 边缘生硬,合成痕迹明显 | P1 | +| 无复制/剪切到新层、Delete 清除、填充/描边 | 选区没有落点,等于没用 | P1 | +| 选区不能约束画笔/橡皮 | 精细化修图做不到 | P1(可后置) | +| 魔棒 / 色彩范围 | 纯色背景一键去背 | P2+(worker 受限,见 §7) | ### 3.2 非破坏性与裁剪(当前是最大架构债) -| 缺口 | 具体表现 | 优先级 | -| --- | --- | --- | -| 裁剪即 flatten | `confirmCrop()` 合成所有可见层 → 重建 `base`/`draw`,图层结构全部丢失 | P2 | -| 裁剪不可撤销 | `S.history = []; S.redoStack = []` | P2 | -| 裁剪丢变换信息 | 只对 `textLayers`/`shapeLayers` 映射 x/y/lw/fontSize,**没处理 `rotation`** | P2 | -| 无「画布大小」/「图像大小」 | 只能靠裁剪栏的「尺寸约束」间接缩放 | P2 | -| 无 90° 旋转 / 水平垂直翻转 / 拉直 | 基础图像操作缺失 | P2 | -| 全幅画布模型 | 每个图层都被钉死在 imgW×imgH,裁剪必须重画所有层 | P0 设计 / P2 实施 | +| 缺口 | 具体表现 | 优先级 | +| ---------------------- | ------------------------------------------------------------------- | ------------- | +| 裁剪即 flatten | `confirmCrop()` 合成所有可见层 → 重建 `base`/`draw`,图层结构全部丢失 | P2 | +| 裁剪不可撤销 | `S.history = []; S.redoStack = []` | P2 | +| 裁剪丢变换信息 | 只对 `textLayers`/`shapeLayers` 映射 x/y/lw/fontSize,**没处理 `rotation`** | P2 | +| 无「画布大小」/「图像大小」 | 只能靠裁剪栏的「尺寸约束」间接缩放 | P2 | +| 无 90° 旋转 / 水平垂直翻转 / 拉直 | 基础图像操作缺失 | P2 | +| 全幅画布模型 | 每个图层都被钉死在 imgW×imgH,裁剪必须重画所有层 | P0 设计 / P2 实施 | ### 3.3 图层 -| 缺口 | 说明 | 优先级 | -| --- | --- | --- | -| 无缩略图 | 图层多了分不清哪张是哪张 | P3 | -| 无混合模式 | 正片叠底/滤色/叠加是合成常用 | P3 | -| 无图层蒙版 | 抠图只能破坏性擦除,不能反悔 | P3 | -| 无重命名 / 多选 / 编组 | 复杂图难管理 | P3 | +| 缺口 | 说明 | 优先级 | +| ------------------ | ----------------------------------------------------------------------------------------------- | ---------- | +| 无缩略图 | 图层多了分不清哪张是哪张 | P3 | +| 无混合模式 | 正片叠底/滤色/叠加是合成常用 | P3 | +| 无图层蒙版 | 抠图只能破坏性擦除,不能反悔 | P3 | +| 无重命名 / 多选 / 编组 | 复杂图难管理 | P3 | | `resetDraw()` 语义歧义 | 「清空标注」只清非 base 层像素,留下空白粘贴层(1.0.5 遗留)⇒ **已裁定改为「全部还原」**:删所有非 base 层 + 清绘制 + 复位变换,一步可撤销;按钮改名「还原原图」 | P0 定语义(已定) | ### 3.4 输出(单张) -| 缺口 | 说明 | 优先级 | -| --- | --- | --- | -| 只有 PNG | 无 JPG/WebP、无质量控制 | P4 | -| 无背景切换(透明 / 白底) | 电商出图要手工来回切换 | P4 | -| 无体积上限策略 | 无法保证 ≤500KB 这类交付规范 ⇒ **已裁定做成可切换预设**(800×800 / 长边 640 / 质量迭代 ≤500KB,存 `ctx.settings`) | P4(随 P1 带上) | -| 无下载 / 复制到系统剪贴板 | 只能回写宿主节点 | P4 | -| 导出步骤偏多 | 覆盖 / 新建 / 退出三个按钮分散,没有「记住上次选择」 | P0 / P4 | -| 导出后图层信息丢失 | 节点里是一张扁平 PNG,下次打开要从头来 | P5(需宿主配合) | +| 缺口 | 说明 | 优先级 | +| -------------- | ------------------------------------------------------------------------------------ | ----------- | +| 只有 PNG | 无 JPG/WebP、无质量控制 | P4 | +| 无背景切换(透明 / 白底) | 电商出图要手工来回切换 | P4 | +| 无体积上限策略 | 无法保证 ≤500KB 这类交付规范 ⇒ **已裁定做成可切换预设**(800×800 / 长边 640 / 质量迭代 ≤500KB,存 `ctx.settings`) | P4(随 P1 带上) | +| 无下载 / 复制到系统剪贴板 | 只能回写宿主节点 | P4 | +| 导出步骤偏多 | 覆盖 / 新建 / 退出三个按钮分散,没有「记住上次选择」 | P0 / P4 | +| 导出后图层信息丢失 | 节点里是一张扁平 PNG,下次打开要从头来 | P5(需宿主配合) | ### 3.5 交互、快捷键、状态 -| 缺口 | 说明 | 优先级 | -| --- | --- | --- | -| 快捷键是数字 1–0 | 无 PS 习惯的 V/B/E/M/L/C、Ctrl+A/C/X/V/J/D/T/Z | P0 映射层 / P5 全量 | -| `Ctrl+V` 已被占用 | 现在恒定「贴为新图层」,与「粘贴选区内容」语义冲突,需明确规则 | P1 | -| Delete 只删文字/形状 | 位图层内容不能一键清除 | P1 | -| 无右键菜单 / 无工具选项栏 / 无状态栏 | 参数散落、当前状态不可见 | P0 | -| 错误提示用 `window.alert` | `pasteImageFromUrl` 失败直接弹窗,无 toast | P0 | -| 图片放置要二次确认 | 拖完还得按 Enter,多一步 | P0(便利性) | -| overlay 单 canvas 多用 | 裁剪遮罩、选中框、笔刷环、放置预览、提示文字全在 `S.overlayCanvas`,共用 `clearOverlay()`;**加蚂蚁线必然互相擦除** | P0 | -| `editor.css` 补丁堆积 | 1340 行,后半段大量 `!important`;工具栏 `position:absolute; top:68px`,撤销按钮 `right:154px` 等魔数;`.iwb-editor-footer` 空且 `display:none`;`.iwb-editor-zoom-hint` 绝对定位 | P0 | -| 无响应式 / 无亮色主题 | 窄窗口下 290px 图层面板 + 44px 工具栏挤压画布 | P5 | -| 关闭即清空 | 无草稿、无二次编辑;`ctx.storage` 只是 localStorage 小 KV | P5 | +| 缺口 | 说明 | 优先级 | +| --------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------ | -------------- | +| 快捷键是数字 1–0 | 无 PS 习惯的 V/B/E/M/L/C、Ctrl+A/C/X/V/J/D/T/Z | P0 映射层 / P5 全量 | +| `Ctrl+V` 已被占用 | 现在恒定「贴为新图层」,与「粘贴选区内容」语义冲突,需明确规则 | P1 | +| Delete 只删文字/形状 | 位图层内容不能一键清除 | P1 | +| 无右键菜单 / 无工具选项栏 / 无状态栏 | 参数散落、当前状态不可见 | P0 | +| 错误提示用 `window.alert` | `pasteImageFromUrl` 失败直接弹窗,无 toast | P0 | +| 图片放置要二次确认 | 拖完还得按 Enter,多一步 | P0(便利性) | +| overlay 单 canvas 多用 | 裁剪遮罩、选中框、笔刷环、放置预览、提示文字全在 `S.overlayCanvas`,共用 `clearOverlay()`;**加蚂蚁线必然互相擦除** | P0 | +| `editor.css` 补丁堆积 | 1340 行,后半段大量 `!important`;工具栏 `position:absolute; top:68px`,撤销按钮 `right:154px` 等魔数;`.iwb-editor-footer` 空且 `display:none`;`.iwb-editor-zoom-hint` 绝对定位 | P0 | +| 无响应式 / 无亮色主题 | 窄窗口下 290px 图层面板 + 44px 工具栏挤压画布 | P5 | +| 关闭即清空 | 无草稿、无二次编辑;`ctx.storage` 只是 localStorage 小 KV | P5 | --- @@ -187,18 +187,18 @@ ### 4.1 便利性准则(验收口径) -| 准则 | 具体做法 | 反例(不做) | -| --- | --- | --- | -| 高频动作 0 层级 | 选区操作浮动条、输出按钮常驻顶栏、图层显隐/锁定就地点击 | 先开菜单 → 子菜单 → 对话框 | -| 低频动作 1 层级 | 「更多 ▾」一次展开,展开后可常驻 | 二级子菜单、向导式多步 | -| 少确认 | 粘贴/导入图片拖完即落层(提供 Esc 撤销,取消 Enter 确认);裁剪确认保留一次(破坏性较大) | 每个操作都弹「确定吗」 | -| 撤销可兜底 | 任何一步都能 Ctrl+Z 回退,包括裁剪与选区清除 | 清空历史、不可撤销的破坏性操作 | -| 状态可见 | 状态栏常驻尺寸/坐标/选区/当前层;toast 取代 `window.alert` | 只在 console 报错、浮层提示一闪而过 | -| 记住选择 | 上次输出格式、背景、尺寸预设、面板开合存 `ctx.settings` | 每次打开都回到默认值 | -| 就地编辑 | 尺寸、比例、羽化直接输入数字;选区可拖动、8 手柄调整、实时显示 W×H | 打开属性面板改参数 | -| 三种入口并存 | 浮动条 / 右键菜单 / 快捷键,任一都会走同一 `execute()` | 三条路径各实现一遍 | -| 画布优先 | 面板默认 260px 且可收起;工具栏 40px;窄窗口自动收面板 | 固定 290px 面板 + 常驻色板挤压画布 | -| 无队列 | 一次一张、一次一个结果;不做批量勾选、批量命名、批量下载 | 输出队列、任务进度条、批量结果列表 | +| 准则 | 具体做法 | 反例(不做) | +| --------- | --------------------------------------------------- | ---------------------- | +| 高频动作 0 层级 | 选区操作浮动条、输出按钮常驻顶栏、图层显隐/锁定就地点击 | 先开菜单 → 子菜单 → 对话框 | +| 低频动作 1 层级 | 「更多 ▾」一次展开,展开后可常驻 | 二级子菜单、向导式多步 | +| 少确认 | 粘贴/导入图片拖完即落层(提供 Esc 撤销,取消 Enter 确认);裁剪确认保留一次(破坏性较大) | 每个操作都弹「确定吗」 | +| 撤销可兜底 | 任何一步都能 Ctrl+Z 回退,包括裁剪与选区清除 | 清空历史、不可撤销的破坏性操作 | +| 状态可见 | 状态栏常驻尺寸/坐标/选区/当前层;toast 取代 `window.alert` | 只在 console 报错、浮层提示一闪而过 | +| 记住选择 | 上次输出格式、背景、尺寸预设、面板开合存 `ctx.settings` | 每次打开都回到默认值 | +| 就地编辑 | 尺寸、比例、羽化直接输入数字;选区可拖动、8 手柄调整、实时显示 W×H | 打开属性面板改参数 | +| 三种入口并存 | 浮动条 / 右键菜单 / 快捷键,任一都会走同一 `execute()` | 三条路径各实现一遍 | +| 画布优先 | 面板默认 260px 且可收起;工具栏 40px;窄窗口自动收面板 | 固定 290px 面板 + 常驻色板挤压画布 | +| 无队列 | 一次一张、一次一个结果;不做批量勾选、批量命名、批量下载 | 输出队列、任务进度条、批量结果列表 | > 「便利」的实现依赖 P0 的命令层:浮动条、右键菜单、快捷键只是三个**视图**,背后必须是同一条 `execute(label, mutator)`,否则便利会变成三套逻辑各修一遍。 @@ -249,16 +249,17 @@ S.selection = { 在 `.iwb-editor-canvas-stack` 内拆成三个独立 canvas,各管各的 `clear()`: -| 层 | 内容 | -| --- | --- | -| `interactionCanvas` | 选中框、8 手柄、旋转弧、放置预览、裁剪遮罩 | -| `selectionCanvas` | 蚂蚁线(rAF 驱动 `lineDashOffset`)、选区外暗化 | -| `cursorCanvas` | 笔刷环、吸管提示光标 | +| 层 | 内容 | +| ------------------- | ---------------------------------- | +| `interactionCanvas` | 选中框、8 手柄、旋转弧、放置预览、裁剪遮罩 | +| `selectionCanvas` | 蚂蚁线(rAF 驱动 `lineDashOffset`)、选区外暗化 | +| `cursorCanvas` | 笔刷环、吸管提示光标 | 现在 `clearOverlay()` 一擦全擦,加蚂蚁线后必然与裁剪框/选中框互相打架,必须先拆。浮动操作条是 **DOM 元素**(不是画在 canvas 上),便于点击、键盘可达与本地化。 ### 5.5 非破坏性文档模型(P2 的选型) + 现有模型是「每个图层 = 全幅 imgW×imgH 画布」,画布尺寸就是图片尺寸,所以裁剪只能重画所有层。两条路线: | 路线 | 做法 | 改动面 | 结论 | diff --git a/image-vectorize/README.md b/image-vectorize/README.md index a504908..30e1b19 100644 --- a/image-vectorize/README.md +++ b/image-vectorize/README.md @@ -1,81 +1,76 @@ # 位图转矢量(image-vectorize) -> ## ⛔ 已下线,未发布(2026-11-05) -> -> 这个插件**已经从线上清单移除、KV 字节已删、宿主的 `wasm-unsafe-eval` 也已收回**。 -> 原因:描摹质量达不到可交付线 —— 中文笔画断裂、抗锯齿边缘起毛刺、浅色块碎层, -> 「看着变矢量但没法用」。引擎参数已调到合理区间(曲线迭代 2 / 颜色精度夹 1–5 / -> 降采样去毛刺 / SVG 层删背景),剩下的是**算法定位**问题:VTracer 适合 logo、线稿、 -> 纯平色块,不适合照片和带抗锯齿的合成图。 -> -> **本目录仅作存档**(代码已验证可用,不要按下面的命令直接发布)。真要复活, -> 需要同时恢复三处:① 宿主 `_headers` 的 `'wasm-unsafe-eval'` ② KV 清单条目 -> ③ 插件管理里勾选启用。删掉本目录也不影响线上任何东西。 +把节点的位图描摹成矢量,输出 SVG 或 PNG 节点。引擎是 **potrace**(Peter Selinger 的二值轮廓算法, +这里用它的 JS 移植 `potrace@2.1.8`,GPL-2.0)—— 和 Inkscape「位图转矢量」同一个内核。 -把节点的位图描摹成矢量,输出 SVG 或透明底 PNG 节点。引擎是 [VTracer](https://github.com/visioncortex/vtracer) -(Rust → WebAssembly,MIT),Inkscape「位图转矢量」的现代替代品:它是原生彩色分层,不像 Inkscape -那样把多次 potrace 结果叠起来(色块交界处常有白缝)。 +## 为什么换了引擎(v0.1 → v0.2,2026-11-05) -## 必须先满足的宿主条件 +v0.1 用 VTracer(彩色分层 + 样条拟合,wasm)。实测在文字图上:**中文笔画断裂、抗锯齿边缘起毛刺、 +浅色块碎成多层** —— 用户的原话是「看着变矢量了但没法用」,当天就下线了。 -宿主 CSP 的 `script-src` 必须包含 **`'wasm-unsafe-eval'`**,否则 wasm 无法编译、插件完全不可用 -(浏览器报 `Compiling or instantiating WebAssembly module violates ...`)。这一项只放行 wasm 编译, -**不**放行字符串 `eval` / `new Function`,因此不等于放宽脚本执行。 +v0.2 换 potrace,并且按用户要求**只做单色 / 灰度**(不做彩色): -宿主仓对应改动:`_headers` → `script-src 'self' 'wasm-unsafe-eval'`。 +| 维度 | VTracer(v0.1) | potrace(v0.2) | +|---|---|---| +| 文字保形 | 笔画会断 | 笔画完整(二值轮廓追踪不猜颜色) | +| 毛刺 | 参数调不掉,得先降采样模糊 | `turdSize` 直接吃掉小于 N 像素的碎片 | +| 颜色 | 彩色分层(也是碎层根源) | 单色 / 灰度 N 层,层数可控 2–5 | +| 依赖 | wasm ⇒ 要放宽 CSP `'wasm-unsafe-eval'` | **纯 JS ⇒ 不动 CSP** | +| 体积 | 238KB(wasm base64 内联) | **116KB** | ## 功能 -- 五个预设:标志/图标、插画/卡通、照片、线稿/黑白、**边缘净化** -- 参数:颜色模式(彩色/黑白)、分层方式(堆叠/镂空)、曲线(样条/多边形)、颜色精度、 - 背景(去除/保留)、边缘净化强度(原尺寸 / 1÷2 / 1÷3 / 1÷4)、输出倍率(1–4× 超采样) -- 高级参数:色层差异、噪点过滤、拐角阈值、路径简化、曲线迭代 -- 预览:按住空格对比原图;面板底部显示路径数 / 颜色数 / 体积 / 耗时 -- 输出:**保存为节点**(透明底 PNG,按输出倍率超采样)· **下载 SVG**(真矢量文件) +- 三个预设:文字 / 线稿(单色)、菜单 / 图文(灰度 3 层)、抠图轮廓(单色 + 强去毛刺) +- 描摹方式:**灰度分层**(层数 2–5)/ **纯单色** +- 高频参数只有两个滑杆:**去小点**(turdSize)、**边缘**(硬朗 / 标准 / 圆润 → alphaMax) +- 高级:阈值(自动 / 手动)、反相(黑底白字用负片)、单色填充色 +- 预览:按住空格对比原图;面板显示路径数 / 层数 / 体积 / 耗时 +- 输出:**保存为节点**(PNG,按输出倍率 1–4× 用矢量重绘)· **下载 SVG**(真矢量) -## 引擎的三个实测坑(改代码前必读) +## 灰度分层为什么自己算阈值 -这三条都是 2026-11-05 在 Chromium 里扫参数扫出来的,写死在 `plugin/engine.js`: +上游 `Posterizer` 的 `steps` 传数字时会跑**直方图多级阈值搜索**,`steps: 5` 实测 **28 秒**(指数级), +不可用。这里改成自己算**等像素量分位**再以数组形式传进去(O(pixels)),5 层也只要几十毫秒。 -1. **`colorPrecision` 语义与官方 CLI 相反**。wasm 侧直接把它当「颜色相似度阈值」,值越大越容易 - 把不同颜色并成一团:≥6 时整张图塌成一个色块,=8 直接 wasm abort。滑杆因此夹在 1–5。 -2. **`maxIterations` ≥3 会过拟合抗锯齿边缘**。一个正圆会被拉成水滴形、圆角矩形的角会被吃掉。 - 默认 2 是实测最稳的值。 -3. **abort 后实例不可复用**。`__wbg_init` 见到已有实例会直接返回坏的那个,所以 `engine.js` 在 - catch 里显式 `__reset_wasm()` 再重建(`plugin/vendor/vtracer.js` 的本地改动就是为了这个钩子)。 +两个必须处理的细节(`engine.js#quantileThresholds`,实测踩过): -另外:**不要**给引擎喂带 alpha 的图。把背景改成透明会触发它的 color keying,透明区被填成 key -color 后与图中相近颜色混淆 —— 实测红圆变形、中文笔画塌成黑块。背景处理放在描摹之后、SVG 层面删 -背景 path(`trace.js#stripBackgroundLayer`)。 +1. **主背景色要排除在人口统计之外**。菜单图底色常占 60–80% 像素,不排除的话切点全落在背景里, + 文字和背景还是分不开(等于白分层)。 +2. **切点必须严格递增**。背景是巨大尖峰,多个切点会算出同一个亮度值 —— 去重后层数变少, + Posterizer 还会算出 0 透明度让整层消失。 -## 毛边净化为什么要降采样 +## 许可 -rembg 那种 ±3px 的毛边,调 `lengthThreshold` / `cornerThreshold` 是抹不掉的 —— 引擎会忠实保留 -每个像素抖动。先把图降到 1÷2~1÷4(双线性插值天然把毛刺平均掉)再描摹,轮廓才真正变光滑。 -代价是小字会糊,所以做成可选强度,默认原尺寸。 +potrace 与其 JS 移植都是 **GPL-2.0**(见 `plugin/vendor/potrace/LICENSE`)。当前用途是**自己用、 +不商用**:GPL 的义务由「分发」触发,自用不触发;且本插件产物是**未混淆的单文件可读源码** +(`src/index.js` 既是产物也是源码),即使哪天对外提供,源码是随附的。 +若将来要商用/闭源分发,换 MIT 的等价实现,或按 GPL 开源该插件。 ## 开发 ```bash -npm run build -- image-vectorize # plugin/ → src/index.js(esbuild IIFE,wasm base64 内联) -npm run validate # 契约校验 -node image-vectorize/tools/harness.mjs # 本地端到端(合成宿主 + 真 Chromium) -node image-vectorize/tools/e2e-site.mjs # 真站(CSP / SRI / 真实 KV) -``` +npm run build -- image-vectorize # plugin/ → src/index.js(esbuild IIFE) +npm run validate # 契约校验 +node image-vectorize/tools/harness.mjs # 本地端到端(合成宿主 + 真 Chromium,30 项) +node image-vectorize/tools/e2e-site.mjs # 真站(KV / SRI / CSP / 真实画布桥) -wasm 以 base64 内联在 `plugin/vendor/wasm-b64.js`,因为宿主发布链路只接受单个 `.js`。 -换 wasm 版本时同时更新 `plugin/vendor/vtracer.{js,wasm}` 并重新生成该文件。 +# 拿真实素材调参数(不进 CI,最快看到效果): +node image-vectorize/tools/trace-cli.mjs ~/Desktop/menu.png --mode gray --levels 3 +node image-vectorize/tools/trace-cli.mjs ~/Desktop/logo.png --mode mono --turd 8 +# → 产物 SVG + 一张「原图 / 结果」对比图(~-/tmp/vz-cli/) +``` 发布: ```bash cp image-vectorize/src/index.js /tmp/plugin-image-vectorize.js cd ../image-workbench-web && node scripts/plugins-publish.mjs /tmp/plugin-image-vectorize.js \ - --version image-vectorize=0.1.1 --upload + --version image-vectorize=0.2.0 --upload ``` ## 已知限制 -- 小字号(<40px)文字描摹后会变形,这是矢量化本身的局限,建议改用「线稿/黑白」或降一级颜色精度 -- 照片类素材色层多、SVG 体积大(几百 KB 到数 MB),必要时用「照片」预设把色层差异调大 -- 超过 2000px 的图会自动降到 2000px 描摹(避免主线程卡死),输出仍按原尺寸渲染 +- **照片不适合**:potrace 只懂明暗,照片会被压成几块灰阶(这不是 bug,是算法定位) +- 小字号(<24px)文字描摹后仍会变形;灰度模式可缓解(把浅色笔画留在单独一层) +- 超过 2000px 的图自动降到 2000px 再描摹(纯 JS 单线程,避免卡主线程) +- 灰度模式的「灰」是 `fill-opacity` 叠出来的(不是多条不同色 path),所以 SVG 里只有一种 fill 色 diff --git a/image-vectorize/package.json b/image-vectorize/package.json index f038190..79ee583 100644 --- a/image-vectorize/package.json +++ b/image-vectorize/package.json @@ -1,8 +1,8 @@ { "name": "@iwb-plugin/image-vectorize", "private": true, - "version": "0.1.1", - "description": "位图转矢量:VTracer(Rust/WebAssembly)描摹,彩色分层或黑白二值,输出 SVG 与透明 PNG 节点;内置「边缘净化」用于清理抠图毛边", + "version": "0.2.0", + "description": "位图转矢量:potrace(纯 JS)单色/灰度描摹,输出 SVG 与 PNG 节点;对文字、logo、线稿保形好,不需要 wasm", "ibwPlugin": { "id": "image-vectorize", "entry": "src/index.js", diff --git a/image-vectorize/plugin/engine.js b/image-vectorize/plugin/engine.js index 436d29f..94525ef 100644 --- a/image-vectorize/plugin/engine.js +++ b/image-vectorize/plugin/engine.js @@ -1,102 +1,172 @@ -/* VTracer 引擎封装。 +/** + * 描摹引擎:potrace(纯 JS,GPL-2.0)—— 单色 / 灰度分层。 * - * 为什么这么薄:vtracer-wasm 只有 `to_svg(pixels, w, h, config)` 一个入口, - * 参数语义在实测中与官方 CLI 有明显偏差(见 CONFIG_LIMITS),所以把它全部收在这里, - * 上层(ui / trace)只跟「业务参数」打交道。 + * 为什么换成 potrace(2026-11-05 用户裁定后的第二版): + * 上一版用 VTracer(彩色分层 + 样条拟合),文字图上会**断笔画、起毛刺、浅色块碎层**, + * 用户实测「看着变矢量但没法用」。potrace 是「二值轮廓追踪 + 曲线拟合」: + * 对 hard edge(文字、logo、线稿)的保形性明显更好,且 turdSize 天生能吃掉小毛刺。 + * 代价是它只懂明暗(不懂颜色),所以只做**单色**与**灰度分层**—— + * 用户明确说了「单色/灰度就够」,不再做彩色。 * - * 实测得出的三条硬约束(2026-11-05,Chromium + 800×800 合成图扫描): - * 1. colorPrecision 的语义与 vtracer CLI 相反:wasm 侧直接把它当「颜色相似度阈值」 - * (is_same_color_a),值越大越容易把不同颜色并成一团。≥6 时整张图会塌成一个色块, - * =8 直接 wasm abort(unreachable)。故夹在 1–5。 - * 2. wasm abort 后实例不可再用,且 __wbg_init 见到已有实例会直接返回坏的, - * 所以 panic 后必须 __reset_wasm() 再重建,否则整个插件从此报错。 - * 3. 像素必须是 RGBA 四通道(ImageData.data 原样),长度 w*h*4。 + * 纯 JS ⇒ 不需要 wasm,**不需要宿主放宽 CSP**(上一版为此加过 'wasm-unsafe-eval', + * 下线时已收回;本版不要再动 CSP)。 + * + * 灰度分层为什么自己算阈值:上游 Posterizer 的 `steps` 传数字时会走直方图多级阈值搜索, + * `steps: 5` 实测 28 秒(指数级),完全不可用。改为自己用**等像素量分位**算好阈值数组 + * 直接传进去(O(pixels)),5 层也只要几十毫秒。 */ 'use strict' -import init, { to_svg, __reset_wasm } from './vendor/vtracer.js' -import wasmB64 from './vendor/wasm-b64.js' +import Potrace from './vendor/potrace/Potrace.js' +import Posterizer from './vendor/potrace/Posterizer.js' -// colorPrecision 安全区间(见文件头第 1 条) -export const COLOR_PRECISION_MIN = 1 -export const COLOR_PRECISION_MAX = 5 +export const MODES = ['gray', 'mono'] +export const LEVELS_MIN = 2 +export const LEVELS_MAX = 5 -let wasmBytes = null -let initPromise = null +/** 描摹上限边(超过就降采样):potrace 是纯 JS 单线程,2000px 以上会明显卡主线程 */ +export const MAX_TRACE_SIDE = 2000 -function decodeWasm() { - if (wasmBytes) return wasmBytes - // 182KB base64 → 137KB 字节;只在首次描摹时解码,避免拖慢插件加载 - const bin = atob(wasmB64) - const out = new Uint8Array(bin.length) - for (let i = 0; i < bin.length; i++) out[i] = bin.charCodeAt(i) - wasmBytes = out - return out +export const DEFAULTS = { + mode: 'gray', // 'gray' 灰度分层 / 'mono' 纯单色 + levels: 3, // 灰度层数(2–5,仅 gray) + threshold: -1, // -1 = 自动(两种模式都支持) + turdSize: 3, // 去小点:面积小于它的碎片直接丢(毛刺/噪点克星) + alphaMax: 1, // 拐角平滑:0 全折线、1 默认、1.334 最圆 + invert: false, // 反相:描摹亮部(黑底白字场景) + color: '#1a1a1a', // mono 的填充色 + outScale: 1, // 输出尺寸倍率(只放大尺寸,不重算曲线) } -function ensureEngine() { - if (!initPromise) { - initPromise = init({ module_or_path: decodeWasm() }).catch(function (error) { - initPromise = null - throw new Error('描摹引擎初始化失败:' + (error && error.message ? error.message : String(error))) - }) - } - return initPromise +const clampInt = (v, min, max, dflt) => { + const n = Math.round(Number(v)) + return Number.isFinite(n) ? Math.min(max, Math.max(min, n)) : dflt } -function clampInt(value, min, max, fallback) { - const n = Math.round(Number(value)) - if (!Number.isFinite(n)) return fallback - return Math.max(min, Math.min(max, n)) -} - -/** 业务参数 → wasm config(字段名 camelCase,枚举小写,与结构体字段一一对应) */ -export function toEngineConfig(p) { +/** 把 UI / 记忆里的松散参数收敛成引擎能吃的确定值 */ +export function normalizeParams(p) { + const src = p || {} return { - binary: Boolean(p.binary), - mode: p.mode === 'polygon' ? 'polygon' : 'spline', - hierarchical: p.hierarchical === 'cutout' ? 'cutout' : 'stacked', - cornerThreshold: Math.max(0, Math.min(180, Number(p.cornerThreshold) || 60)), - lengthThreshold: Math.max(0.1, Math.min(10, Number(p.lengthThreshold) || 3.5)), - // maxIterations 是曲线拟合的迭代次数。上游 CLI 默认 10,但实测只要 ≥3 就会过拟合抗锯齿边缘: - // 一个正圆被拉成水滴形、圆角矩形的角被吃掉。2 是实测最稳的值(圆保持圆、直角保持直)。 - maxIterations: clampInt(p.maxIterations, 1, 10, 2), - spliceThreshold: 45, - filterSpeckle: clampInt(p.filterSpeckle, 0, 128, 4), - // 黑白模式没有颜色聚类,这两个字段只是结构体必填,给安全值即可 - colorPrecision: clampInt(p.colorPrecision, COLOR_PRECISION_MIN, COLOR_PRECISION_MAX, 2), - layerDifference: clampInt(p.layerDifference, 0, 64, 16), - pathPrecision: 8, + 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 + })(), + 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)), } } /** - * 描摹一次。 - * @param {Uint8ClampedArray|Uint8Array} rgba 长度必须等于 w*h*4 - * @returns {Promise<{svg: string, ms: number}>} + * 等像素量分位阈值:把亮度直方图按像素数切成 levels 段,返回 levels-1 个切点。 + * + * 两个必须处理的坑(实测,不是理论问题): + * 1. **主背景色要排除在人口统计之外**。电商图/菜单图里底色常占 60–80% 像素, + * 不排除的话三个切点里有两个会落在背景里,文字还是跟背景分不开(等于没分层)。 + * 2. **切点必须严格递增**。背景是一个巨大的尖峰,多个切点会算出同一个亮度值, + * 去重后层数变少(Posterizer 还会算出 0 透明度,整层消失)。 */ -export async function tracePixels(rgba, width, height, params) { - const w = Math.round(width) - const h = Math.round(height) - if (!(w > 0) || !(h > 0)) throw new Error('图片尺寸无效') - if (!rgba || rgba.length !== w * h * 4) throw new Error('像素数据长度与尺寸不符') - - await ensureEngine() - const config = toEngineConfig(params) - const pixels = rgba instanceof Uint8Array ? rgba : new Uint8Array(rgba.buffer, rgba.byteOffset, rgba.length) - const started = (typeof performance !== 'undefined' ? performance.now() : Date.now()) - - try { - const svg = to_svg(pixels, w, h, config) - const ms = Math.round((typeof performance !== 'undefined' ? performance.now() : Date.now()) - started) - return { svg, ms } - } catch (error) { - // wasm abort 后实例已损坏,必须复位,否则下一次调用还是同一个坏实例 - initPromise = null - try { __reset_wasm() } catch (e) { /* 复位本身失败也只能继续抛原始错误 */ } - throw new Error( - '描摹失败(引擎内部异常):' + (error && error.message ? error.message : String(error)) + - '。请调大「颜色精度」的容错或换「黑白」模式重试' - ) +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: 0.2, + 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: 0.2, + 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(/ { - const meta = PARAM_META[key] - const n = Number(p[key]) - if (!Number.isFinite(n)) return fallback - return Math.max(meta.min, Math.min(meta.max, n)) - } - return { - binary: Boolean(p.binary), - hierarchical: p.hierarchical === 'cutout' ? 'cutout' : 'stacked', - mode: p.mode === 'polygon' ? 'polygon' : 'spline', - colorPrecision: Math.round(num('colorPrecision', 2)), - layerDifference: Math.round(num('layerDifference', 16)), - filterSpeckle: Math.round(num('filterSpeckle', 4)), - cornerThreshold: num('cornerThreshold', 60), - lengthThreshold: num('lengthThreshold', 3.5), - maxIterations: Math.round(num('maxIterations', 2)), - denoise: Math.max(1, Math.min(4, Math.round(Number(p.denoise) || 1))), - bg: p.bg === 'keep' ? 'keep' : 'auto', - } -} - -/** - * 采样画布四角颜色(用于判断「有没有统一背景」)。 - * @returns {[number,number,number]|null} 四角一致时返回该颜色,否则 null - */ -export function cornerColor(imageData, tolerance) { - const w = imageData.width - const h = imageData.height - const px = imageData.data - const tol = tolerance === undefined ? 20 : tolerance - const at = function (x, y) { - const i = (y * w + x) * 4 - return [px[i], px[i + 1], px[i + 2], px[i + 3]] - } - const list = [at(0, 0), at(w - 1, 0), at(0, h - 1), at(w - 1, h - 1)].filter(function (c) { return c[3] > 8 }) - if (list.length < 3) return null - const base = list[0] - for (const c of list) { - if (Math.abs(c[0] - base[0]) > tol || Math.abs(c[1] - base[1]) > tol || Math.abs(c[2] - base[2]) > tol) return null - } - return [base[0], base[1], base[2]] -} - -function hexToRgb(hex) { - const m = /^#([0-9a-f]{6})$/i.exec(hex) - if (!m) return null - const n = parseInt(m[1], 16) - return [(n >> 16) & 255, (n >> 8) & 255, n & 255] -} - -/** 估计一条 path 的实际包围盒:d 里的坐标对 + transform 的 translate 平移 */ -function pathExtent(d, tx, ty) { - const nums = String(d).match(/-?\d+(?:\.\d+)?/g) - if (!nums || nums.length < 4) return null - let minX = Infinity, maxX = -Infinity, minY = Infinity, maxY = -Infinity - for (let i = 0; i + 1 < nums.length; i += 2) { - const x = Number(nums[i]) + tx - const y = Number(nums[i + 1]) + ty - if (!Number.isFinite(x) || !Number.isFinite(y)) continue - if (x < minX) minX = x - if (x > maxX) maxX = x - if (y < minY) minY = y - if (y > maxY) maxY = y - } - if (!Number.isFinite(minX) || !Number.isFinite(minY)) return null - return { minX, maxX, minY, maxY } -} - -/** - * 从描摹结果里剔掉「铺满画布的背景层」。 - * - * 为什么在 SVG 层面做,而不是描摹前把背景像素改成透明(实测走过的弯路): - * 喂给引擎带 alpha 的图会触发它的 color keying,透明区被填成 key color 后 - * 与图中相近的颜色混淆 —— 实测红圆直接变形、中文笔画塌成黑块。 - * 保持描摹输入是原图,只在输出里删掉那一条背景 path,主体质量不受任何影响。 - * - * @param {string} svg 引擎输出 - * @param {number} w 描摹宽 - * @param {number} h 描摹高 - * @param {[number,number,number]|null} bgRgb 四角背景色(null 则只按几何判断) - * @returns {{svg: string, removed: boolean}} - */ -export function stripBackgroundLayer(svg, w, h, bgRgb) { - const text = String(svg) - const start = text.indexOf('', start) - if (end < 0) return { svg: text, removed: false } - const tag = text.slice(start, end + 2) - - const fillMatch = /fill="(#[0-9A-Fa-f]{6})"/.exec(tag) - const dMatch = /d="([^"]+)"/.exec(tag) - if (!fillMatch || !dMatch) return { svg: text, removed: false } - - if (bgRgb) { - const rgb = hexToRgb(fillMatch[1]) - if (!rgb) return { svg: text, removed: false } - // 背景层颜色必须与四角采样接近,否则说明第一条不是背景(透明底图/贴边主体) - const diff = Math.max(Math.abs(rgb[0] - bgRgb[0]), Math.abs(rgb[1] - bgRgb[1]), Math.abs(rgb[2] - bgRgb[2])) - if (diff > 24) return { svg: text, removed: false } - } - - const tr = /translate\(\s*(-?[\d.]+)\s*[, ]\s*(-?[\d.]+)\s*\)/.exec(tag) - const ext = pathExtent(dMatch[1], tr ? Number(tr[1]) : 0, tr ? Number(tr[2]) : 0) - if (!ext) return { svg: text, removed: false } - - const coverW = (ext.maxX - ext.minX) / w - const coverH = (ext.maxY - ext.minY) / h - // 覆盖 ≥85% 画布才算背景;主体满幅的图(纯色块)删掉会变成空白,靠颜色比对已经挡了一层 - if (coverW < 0.85 || coverH < 0.85) return { svg: text, removed: false } - - return { svg: text.slice(0, start) + text.slice(end + 2), removed: true } -} - -export function loadImage(src) { +/** 读 data URL 成 (走浏览器解码,与画布语义一致) */ +export function loadImage(dataUrl) { return new Promise(function (resolve, reject) { const img = new Image() img.onload = function () { resolve(img) } img.onerror = function () { reject(new Error('图片解码失败')) } - img.src = src + img.src = dataUrl }) } /** - * 预处理:按 denoise 倍数降采样(并把超大图夹到 MAX_TRACE_SIDE 内)。 - * @returns {{ canvas: HTMLCanvasElement, w: number, h: number, scale: number, clamped: boolean }} + * 准备描摹用的像素:potrace 是单线程纯 JS,超过 MAX_TRACE_SIDE 会明显卡主线程, + * 所以先按长边夹取(**只缩不放**)。 + * @returns {{canvas:HTMLCanvasElement, w:number, h:number, srcW:number, srcH:number, clamped:boolean}} */ -export function prepareSource(img, denoise) { +export function prepareSource(img) { const srcW = img.naturalWidth || img.width const srcH = img.naturalHeight || img.height - if (!(srcW > 0) || !(srcH > 0)) throw new Error('图片尺寸无效') - - let scale = 1 / Math.max(1, Math.min(4, Math.round(denoise) || 1)) - const clamped = Math.max(srcW, srcH) * scale > MAX_TRACE_SIDE - if (clamped) scale = MAX_TRACE_SIDE / Math.max(srcW, srcH) - - const w = Math.max(1, Math.round(srcW * scale)) - const h = Math.max(1, Math.round(srcH * scale)) + const longSide = Math.max(srcW, srcH) + const k = longSide > MAX_TRACE_SIDE ? MAX_TRACE_SIDE / longSide : 1 + const w = Math.max(1, Math.round(srcW * k)) + const h = Math.max(1, Math.round(srcH * k)) const canvas = document.createElement('canvas') canvas.width = w canvas.height = h - const g = canvas.getContext('2d') - g.imageSmoothingEnabled = true - g.imageSmoothingQuality = 'high' - g.drawImage(img, 0, 0, w, h) - return { canvas, w, h, scale: w / srcW, clamped, srcW, srcH } + const ctx = canvas.getContext('2d', { willReadFrequently: true }) + ctx.imageSmoothingEnabled = true + ctx.drawImage(img, 0, 0, w, h) + return { canvas, w, h, srcW, srcH, clamped: k < 1 } } -/** - * vtracer 产出的 svg 只有 width/height 没有 viewBox(描摹尺寸即画布尺寸)。 - * 降采样后必须补 viewBox 才能放大回原始尺寸而不失真,否则浏览器按降采样尺寸渲染。 - */ -export function withViewBox(svg, tracedW, tracedH, outW, outH) { - return String(svg).replace(/]*)>/, function (_m, attrs) { - const rest = attrs.replace(/\s(?:width|height|viewBox)="[^"]*"/g, '') - return '' - }) -} - -/** SVG → 位图。走 blob: URL(宿主 img-src 放行 blob:,且不污染画布)。 */ +/** SVG 字符串 → (导出时把矢量光栅化) */ export function svgToImage(svg) { return new Promise(function (resolve, reject) { const blob = new Blob([svg], { type: 'image/svg+xml;charset=utf-8' }) const url = URL.createObjectURL(blob) const img = new Image() img.onload = function () { URL.revokeObjectURL(url); resolve(img) } - img.onerror = function () { URL.revokeObjectURL(url); reject(new Error('矢量结果渲染失败')) } + img.onerror = function () { URL.revokeObjectURL(url); reject(new Error('矢量渲染失败')) } img.src = url }) } -/** SVG → 透明底 PNG Blob(outScale 倍超采样,边缘抗锯齿更好) */ +/** + * 把矢量结果光栅化成 PNG(保存为节点用)。outScale 只影响像素尺寸 —— + * 曲线按 viewBox 缩放渲染,所以 2× 是真的更清晰,不是插值放大。 + */ export async function svgToPngBlob(svg, baseW, baseH, outScale) { const img = await svgToImage(svg) - const scale = Math.max(1, Math.min(4, Math.round(outScale) || 1)) - const w = Math.round(baseW * scale) - const h = Math.round(baseH * scale) + const k = Math.max(1, Math.min(4, Number(outScale) || 1)) + const w = Math.max(1, Math.round(baseW * k)) + const h = Math.max(1, Math.round(baseH * k)) const canvas = document.createElement('canvas') canvas.width = w canvas.height = h - const g = canvas.getContext('2d') - g.clearRect(0, 0, w, h) - g.drawImage(img, 0, 0, w, h) + const ctx = canvas.getContext('2d') + ctx.drawImage(img, 0, 0, w, h) return new Promise(function (resolve, reject) { canvas.toBlob(function (blob) { if (blob) resolve(blob) @@ -253,16 +75,13 @@ export async function svgToPngBlob(svg, baseW, baseH, outScale) { }) } -/** 统计:路径数、文件体积、颜色数 —— 面板底部展示,让「参数调大了会怎样」可见 */ +/** 统计:路径数、填充色数、字节数(面板上「体积」那个数字) */ export function svgStats(svg) { - const s = String(svg) - const paths = (s.match(/ 而不是 innerHTML 插 SVG —— 宿主 CSP 下更安全,也避免每次重绘解析 DOM; - * 3. 描摹是同步 wasm 调用,重入保护用 busy/pending 两态,滑杆连拖时只跑最后一次; - * 4. 调参的记忆走 ctx.settings(宿主命名空间 KV),下次打开直接回到上次的参数与预设。 + * 3. potrace 是**同步**纯 JS(800px 几十毫秒),所以没有上一版那种 busy/pending 重入状态机, + * 只保留 150ms 防抖 + seq 票据(关闭时让在途回调失效); + * 4. 参数记忆走 ctx.settings(宿主命名空间 KV),下次打开回到上次的参数。 + * + * 面板刻意做小:用户只做单色/灰度,高频就「方式 + 层数 + 去小点」三个, + * 阈值/反相/颜色收进高级(0 层级优先,低频 1 层级)。 */ 'use strict' -import { PRESETS, PARAM_META, clampParams, loadImage, prepareSource, cornerColor, stripBackgroundLayer, withViewBox, svgToPngBlob, svgStats, denoiseLabel } from './trace.js' -import { tracePixels } from './engine.js' +import { DEFAULTS, LEVELS_MIN, LEVELS_MAX, normalizeParams } from './engine.js' +import { loadImage, prepareSource, svgToPngBlob, svgStats } from './trace.js' +import { traceImageData } from './engine.js' -const SETTING_KEYS = ['preset', 'binary', 'hierarchical', 'mode', 'colorPrecision', 'layerDifference', 'filterSpeckle', 'cornerThreshold', 'lengthThreshold', 'maxIterations', 'denoise', 'bg', 'outScale'] +const SETTING_KEYS = ['preset', 'mode', 'levels', 'threshold', 'turdSize', 'alphaMax', 'invert', 'color', 'outScale'] -const MODE_LABELS = { - hierarchical: [['stacked', '堆叠'], ['cutout', '镂空']], - mode: [['spline', '样条'], ['polygon', '多边形']], +/** 三个预设:都围绕「自己出图」的实际场景,不放没用的组合 */ +const PRESETS = { + text: { label: '文字 / 线稿', hint: '单色 · 保笔画', mode: 'mono', turdSize: 2, alphaMax: 1, levels: 3 }, + menu: { label: '菜单 / 图文', hint: '灰度 3 层', mode: 'gray', levels: 3, turdSize: 4, alphaMax: 1 }, + cutout: { label: '抠图轮廓', hint: '单色 · 去毛刺', mode: 'mono', turdSize: 12, alphaMax: 1.1, levels: 3 }, +} + +const HINTS = { + turdSize: '抹掉小于该像素面积的碎片(毛刺 / 噪点)', + alphaMax: '越小越硬朗(多折线),越大越圆', } function esc(s) { @@ -24,24 +36,23 @@ function esc(s) { }) } -function segHTML(name, options, current) { +function segHTML(group, options, current) { return options.map(function (pair) { - const active = pair[0] === current ? ' active' : '' - return '' + const active = String(pair[0]) === String(current) ? ' active' : '' + return '' }).join('') } -function rangeHTML(name, value) { - const meta = PARAM_META[name] +function rangeHTML(name, label, min, max, step, value, hint) { return '
' + - '
' + esc(meta.label) + '
' + + '
' + esc(label) + (hint ? '' + esc(hint) + '' : '') + '
' + '
' + - '' + + '' + '' + value + '' + '
' } -function panelHTML(params, preset) { +function panelHTML(params, preset, outScale) { const presets = Object.keys(PRESETS).map(function (key) { const p = PRESETS[key] return '' + - '' + - '
分层方式
' + segHTML('hierarchical', MODE_LABELS.hierarchical, params.hierarchical) + '
' + - '
曲线
' + segHTML('mode', MODE_LABELS.mode, params.mode) + '
' + - '' + - - '
' + - rangeHTML('colorPrecision', params.colorPrecision) + - '
背景贴合画布边缘的同色
' + - '' + - '
' + - '
' + - - '
' + - '
边缘净化先降采样再描摹
' + - [1, 2, 3, 4].map(function (n) { return '' }).join('') + + '
描摹方式
' + + segHTML('mode', [['gray', '灰度分层'], ['mono', '纯单色']], params.mode) + '
' + + '
层数多一层,浅色块更容易分离
' + + [2, 3, 4, 5].map(function (n) { return '' }).join('') + '
' + - '
输出倍率PNG 超采样
' + + '
' + + + '
' + + rangeHTML('turdSize', '去小点', 0, 40, 1, params.turdSize, HINTS.turdSize) + + '
边缘
' + + '' + + '' + + '
' + + '
' + + + '
' + + '
输出倍率PNG 按矢量重绘,真清晰
' + [1, 2, 3, 4].map(function (n) { return '' }).join('') + '
' + '
' + @@ -78,7 +87,7 @@ function panelHTML(params, preset) { '
' + '
' + '– 路径' + - '– 颜色' + + '– 层' + '–' + '–' + '
' + @@ -87,17 +96,20 @@ function panelHTML(params, preset) { '
' + '' + '' + '
' } -function viewHTML(title, name) { +function viewHTML(name) { return '' + '
' + '
' } +/** 边缘预设 → alphaMax(越圆 alphaMax 越大) */ +const ALPHA_TONE = { hard: 0.4, normal: 1, round: 1.2 } +const toneOf = (alphaMax) => (alphaMax <= 0.6 ? 'hard' : alphaMax >= 1.1 ? 'round' : 'normal') + export function createVectorizer(options) { const settings = options.settings const onSaveNode = options.onSaveNode @@ -129,13 +145,11 @@ export function createVectorizer(options) { let root = null let els = null let source = null - let params = clampParams({}) - let preset = 'logo' + let params = normalizeParams(DEFAULTS) + let preset = 'text' let outScale = 2 let currentSvg = '' let currentBlobUrl = '' - let busy = false - let pending = false let seq = 0 let debounceTimer = 0 let spaceDown = false @@ -149,7 +163,7 @@ export function createVectorizer(options) { let value try { value = settings.get(key) } catch (e) { continue } if (value === undefined || value === null || value === '') continue - if (key === 'binary') value = value === true || value === 'true' || value === 1 || value === '1' + if (key === 'invert') value = value === true || value === 'true' || value === 1 || value === '1' out[key] = value } return out @@ -159,17 +173,13 @@ export function createVectorizer(options) { if (!settings || typeof settings.set !== 'function') return try { settings.set('preset', preset) - settings.set('binary', params.binary) - settings.set('hierarchical', params.hierarchical) settings.set('mode', params.mode) - settings.set('colorPrecision', params.colorPrecision) - settings.set('layerDifference', params.layerDifference) - settings.set('filterSpeckle', params.filterSpeckle) - settings.set('cornerThreshold', params.cornerThreshold) - settings.set('lengthThreshold', params.lengthThreshold) - settings.set('maxIterations', params.maxIterations) - settings.set('denoise', params.denoise) - settings.set('bg', params.bg) + settings.set('levels', params.levels) + settings.set('threshold', params.threshold) + settings.set('turdSize', params.turdSize) + settings.set('alphaMax', params.alphaMax) + settings.set('invert', params.invert) + settings.set('color', params.color) settings.set('outScale', outScale) } catch (e) { /* 记忆失败不影响主流程 */ } } @@ -185,15 +195,15 @@ export function createVectorizer(options) { els.statusText.textContent = text || '' } - function setStats(stats, ms) { + function setStats(stats, ms, levels) { if (!els) return const put = function (key, text) { const node = els.panel.querySelector('[data-stat="' + key + '"]') if (node) node.textContent = text } - if (!stats) { put('paths', '–'); put('colors', '–'); put('bytes', '–'); put('ms', '–'); return } + if (!stats) { put('paths', '–'); put('levels', '–'); put('bytes', '–'); put('ms', '–'); return } put('paths', String(stats.paths)) - put('colors', String(stats.colors)) + put('levels', String(levels || 1)) put('bytes', stats.bytes >= 1024 * 1024 ? (stats.bytes / 1024 / 1024).toFixed(1) + 'MB' : Math.round(stats.bytes / 1024) + 'KB') @@ -209,22 +219,39 @@ export function createVectorizer(options) { }) panel.querySelectorAll('[data-param]').forEach(function (input) { const key = input.dataset.param - input.value = params[key] + input.value = key === 'threshold' && params.threshold < 0 ? 128 : params[key] const out = panel.querySelector('[data-val="' + key + '"]') - if (out) out.textContent = params[key] - // 黑白模式不使用颜色聚类,颜色精度/色层差异在引擎里不生效 —— 直接禁用而不是假装可调 - const dead = params.binary && (key === 'colorPrecision' || key === 'layerDifference') - input.disabled = dead - if (out) out.parentElement.style.opacity = dead ? '0.45' : '' + if (out) out.textContent = input.value }) - panel.querySelectorAll('[data-seg-group="binary"] button').forEach(function (btn) { - btn.classList.toggle('active', (btn.dataset.value === 'binary') === params.binary) + // 层数只在灰度下有含义;颜色只在单色下有含义 —— 直接隐藏而不是假装可调 + panel.querySelectorAll('[data-only="gray"]').forEach(function (row) { + row.hidden = params.mode !== 'gray' }) - for (const group of ['hierarchical', 'mode', 'bg', 'denoise', 'outScale']) { - const current = group === 'outScale' ? String(outScale) : String(params[group]) - panel.querySelectorAll('[data-seg-group="' + group + '"] button').forEach(function (btn) { - btn.classList.toggle('active', btn.dataset.value === current) - }) + panel.querySelectorAll('[data-seg-group="levels"] button').forEach(function (btn) { + btn.classList.toggle('active', Number(btn.dataset.value) === params.levels) + }) + panel.querySelectorAll('[data-seg-group="mode"] button').forEach(function (btn) { + btn.classList.toggle('active', btn.dataset.value === params.mode) + }) + panel.querySelectorAll('[data-seg-group="alphaTone"] button').forEach(function (btn) { + btn.classList.toggle('active', btn.dataset.value === toneOf(params.alphaMax)) + }) + panel.querySelectorAll('[data-seg-group="invert"] button').forEach(function (btn) { + btn.classList.toggle('active', (btn.dataset.value === '1') === params.invert) + }) + panel.querySelectorAll('[data-seg-group="thrMode"] button').forEach(function (btn) { + btn.classList.toggle('active', (btn.dataset.value === 'manual') === (params.threshold >= 0)) + }) + panel.querySelectorAll('[data-seg-group="outScale"] button').forEach(function (btn) { + btn.classList.toggle('active', Number(btn.dataset.value) === outScale) + }) + const thrRow = panel.querySelector('[data-thr-row]') + if (thrRow) thrRow.hidden = params.threshold < 0 + const colorInput = panel.querySelector('[data-color="color"]') + if (colorInput) { + colorInput.value = params.color + colorInput.disabled = params.mode !== 'mono' + colorInput.parentElement.style.opacity = params.mode === 'mono' ? '' : '0.45' } } @@ -247,65 +274,44 @@ export function createVectorizer(options) { function updateBadge() { if (!els) return - const original = spaceDown - els.vector.hidden = original - els.original.hidden = !original - els.badge.textContent = original ? '原图' : '矢量预览' + els.vector.hidden = spaceDown + els.original.hidden = !spaceDown + els.badge.textContent = spaceDown ? '原图' : '矢量预览' } // ---------- 描摹 ---------- - async function retrace() { + function retrace() { if (!source) return - if (busy) { pending = true; return } - busy = true const ticket = ++seq - setStatus('busy', '描摹中…') try { - const prepared = prepareSource(source.img, params.denoise) - const g = prepared.canvas.getContext('2d') - const data = g.getImageData(0, 0, prepared.w, prepared.h) - // 背景处理放在描摹之后、SVG 层面:喂给引擎带 alpha 的图会触发它的 color keying, - // 实测会让主体变形(红圆走形、中文笔画塌成黑块),所以描摹输入永远是原图。 - const bgRgb = params.bg === 'auto' ? cornerColor(data, 20) : null - const out = await tracePixels(data.data, prepared.w, prepared.h, params) + const prepared = prepareSource(source.img) + const ctx = prepared.canvas.getContext('2d', { willReadFrequently: true }) + const data = ctx.getImageData(0, 0, prepared.w, prepared.h) + const out = traceImageData(data, params) if (ticket !== seq || !els) return - const w = prepared.srcW - const h = prepared.srcH - let traced = out.svg - let bgRemoved = false - if (bgRgb) { - const stripped = stripBackgroundLayer(traced, prepared.w, prepared.h, bgRgb) - traced = stripped.svg - bgRemoved = stripped.removed - } - currentSvg = withViewBox(traced, prepared.w, prepared.h, w, h) + currentSvg = out.svg showVector(currentSvg) - setStats(svgStats(currentSvg), out.ms) - const notes = [] - if (bgRemoved) notes.push('已去掉背景') - if (prepared.clamped) notes.push('大图已降到 ' + prepared.w + '×' + prepared.h) - if (notes.length) { - setStatus('busy', notes.join(' · ')) + setStats(svgStats(currentSvg), out.ms, out.levels) + setStatus(null) + if (prepared.clamped) { + setStatus('busy', '大图已降到 ' + prepared.w + '×' + prepared.h + ' 再描摹') window.setTimeout(function () { if (ticket === seq) setStatus(null) }, 2600) - } else { - setStatus(null) } - els.meta.textContent = source.name + ' · ' + w + '×' + h + els.meta.textContent = source.name + ' · ' + prepared.srcW + '×' + prepared.srcH } catch (error) { if (ticket !== seq) return currentSvg = '' setStats(null) - setStatus('error', error && error.message ? error.message : String(error)) - } finally { - busy = false - if (pending) { pending = false; retrace() } + const msg = error && error.message ? error.message : String(error) + setStatus('error', '描摹失败:' + msg) + if (typeof onError === 'function') onError(error) } } function scheduleRetrace() { window.clearTimeout(debounceTimer) - debounceTimer = window.setTimeout(function () { writeSettings(); retrace() }, 150) + debounceTimer = window.setTimeout(function () { writeSettings(); retrace() }, 120) } // ---------- 输出 ---------- @@ -329,7 +335,7 @@ export function createVectorizer(options) { const label = button.textContent button.textContent = '生成中…' try { - const prepared = prepareSource(source.img, params.denoise) + const prepared = prepareSource(source.img) const blob = await svgToPngBlob(currentSvg, prepared.srcW, prepared.srcH, outScale) await onSaveNode(blob, source.base + '.png') close() @@ -343,16 +349,26 @@ export function createVectorizer(options) { // ---------- 事件 ---------- function onPanelInput(event) { + const color = event.target.closest('[data-color]') + if (color && els.panel.contains(color)) { + if (!/^#[0-9a-f]{6}$/i.test(color.value)) return + params.color = color.value + preset = '' + scheduleRetrace() + return + } const input = event.target.closest('[data-param]') if (!input || !els.panel.contains(input)) return const key = input.dataset.param - const meta = PARAM_META[key] const raw = Number(input.value) - params[key] = Math.max(meta.min, Math.min(meta.max, Number.isFinite(raw) ? raw : params[key])) + if (key === 'threshold') { + params.threshold = Math.max(0, Math.min(255, Math.round(raw))) + } else if (key === 'turdSize') { + params.turdSize = Math.max(0, Math.min(40, Math.round(raw))) + } const out = els.panel.querySelector('[data-val="' + key + '"]') - if (out) out.textContent = params[key] - // 手动调参即脱离预设(预设只是参数组合的快捷方式) - if (preset) { preset = ''; syncControls() } + if (out) out.textContent = input.value + preset = '' scheduleRetrace() } @@ -375,7 +391,7 @@ export function createVectorizer(options) { const key = presetBtn.dataset.preset if (!PRESETS[key]) return preset = key - params = clampParams(PRESETS[key]) + params = normalizeParams(Object.assign({}, params, PRESETS[key])) syncControls() writeSettings() retrace() @@ -386,23 +402,26 @@ export function createVectorizer(options) { if (!seg) return const name = seg.dataset.seg const value = seg.dataset.value - if (name === 'binary') { - params.binary = value === 'binary' + if (name === 'mode') { + params.mode = value === 'mono' ? 'mono' : 'gray' preset = '' - } else if (name === 'denoise') { - params.denoise = Number(value) + } else if (name === 'levels') { + params.levels = Math.max(LEVELS_MIN, Math.min(LEVELS_MAX, Number(value) || 3)) preset = '' - } else if (name === 'bg') { - params.bg = value === 'keep' ? 'keep' : 'auto' + } else if (name === 'alphaTone') { + params.alphaMax = ALPHA_TONE[value] === undefined ? 1 : ALPHA_TONE[value] + preset = '' + } else if (name === 'invert') { + params.invert = value === '1' + preset = '' + } else if (name === 'thrMode') { + params.threshold = value === 'manual' ? 128 : -1 preset = '' } else if (name === 'outScale') { - outScale = Number(value) - syncControls() + outScale = Math.max(1, Math.min(4, Number(value) || 1)) writeSettings() + syncControls() return - } else if (name === 'hierarchical' || name === 'mode') { - params[name] = value - preset = '' } else { return } @@ -428,7 +447,6 @@ export function createVectorizer(options) { return } if (event.code === 'Space' && !spaceDown && !event.repeat) { - // 空格对比原图:只在焦点不在输入控件时生效 const tag = (event.target && event.target.tagName) || '' if (tag === 'INPUT' || tag === 'TEXTAREA') return event.preventDefault() @@ -450,7 +468,8 @@ export function createVectorizer(options) { function close() { if (!root) return - seq++ // 让在途描摹的回调全部失效(否则关闭后仍会回写已移除的 DOM) + seq++ + window.clearTimeout(debounceTimer) document.removeEventListener('keydown', onKeyDown, true) document.removeEventListener('keyup', onKeyUp, true) window.removeEventListener('blur', onBlur) @@ -467,23 +486,17 @@ export function createVectorizer(options) { async function open(request) { if (root) close() const stored = readSettings() - preset = PRESETS[stored.preset] ? stored.preset : 'logo' - params = clampParams(Object.assign({}, PRESETS[preset], stored)) + preset = PRESETS[stored.preset] ? stored.preset : 'text' + params = normalizeParams(Object.assign({}, DEFAULTS, PRESETS[preset], stored)) outScale = Math.max(1, Math.min(4, Math.round(Number(stored.outScale) || 2))) const img = await loadImage(request.imageDataUrl) const name = String(request.name || 'image.png') const base = name.replace(/\.[^.]+$/, '') || 'image' - source = { - img, - name, - base, - srcW: img.naturalWidth || img.width, - srcH: img.naturalHeight || img.height, - } + source = { img, name, base, srcW: img.naturalWidth || img.width, srcH: img.naturalHeight || img.height } root = document.createElement('div') - root.innerHTML = viewHTML('位图转矢量', name) + root.innerHTML = viewHTML(name) document.body.appendChild(root) els = { root, @@ -498,7 +511,7 @@ export function createVectorizer(options) { } els.original.src = request.imageDataUrl els.meta.textContent = name + ' · ' + source.srcW + '×' + source.srcH - els.panel.innerHTML = panelHTML(params, preset) + els.panel.innerHTML = panelHTML(params, preset, outScale) root.addEventListener('click', onRootClick) els.panel.addEventListener('input', onPanelInput) diff --git a/image-vectorize/plugin/vendor/VTracer-LICENSE.txt b/image-vectorize/plugin/vendor/VTracer-LICENSE.txt deleted file mode 100644 index 74dc9ff..0000000 --- a/image-vectorize/plugin/vendor/VTracer-LICENSE.txt +++ /dev/null @@ -1,21 +0,0 @@ -MIT License - -Copyright (c) 2025 jsscheller - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. \ No newline at end of file diff --git a/image-vectorize/plugin/vendor/potrace/LICENSE b/image-vectorize/plugin/vendor/potrace/LICENSE new file mode 100644 index 0000000..23cb790 --- /dev/null +++ b/image-vectorize/plugin/vendor/potrace/LICENSE @@ -0,0 +1,339 @@ + GNU GENERAL PUBLIC LICENSE + Version 2, June 1991 + + Copyright (C) 1989, 1991 Free Software Foundation, Inc., + 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The licenses for most software are designed to take away your +freedom to share and change it. By contrast, the GNU General Public +License is intended to guarantee your freedom to share and change free +software--to make sure the software is free for all its users. This +General Public License applies to most of the Free Software +Foundation's software and to any other program whose authors commit to +using it. (Some other Free Software Foundation software is covered by +the GNU Lesser General Public License instead.) You can apply it to +your programs, too. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +this service if you wish), that you receive source code or can get it +if you want it, that you can change the software or use pieces of it +in new free programs; and that you know you can do these things. + + To protect your rights, we need to make restrictions that forbid +anyone to deny you these rights or to ask you to surrender the rights. +These restrictions translate to certain responsibilities for you if you +distribute copies of the software, or if you modify it. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must give the recipients all the rights that +you have. You must make sure that they, too, receive or can get the +source code. And you must show them these terms so they know their +rights. + + We protect your rights with two steps: (1) copyright the software, and +(2) offer you this license which gives you legal permission to copy, +distribute and/or modify the software. + + Also, for each author's protection and ours, we want to make certain +that everyone understands that there is no warranty for this free +software. If the software is modified by someone else and passed on, we +want its recipients to know that what they have is not the original, so +that any problems introduced by others will not reflect on the original +authors' reputations. + + Finally, any free program is threatened constantly by software +patents. We wish to avoid the danger that redistributors of a free +program will individually obtain patent licenses, in effect making the +program proprietary. To prevent this, we have made it clear that any +patent must be licensed for everyone's free use or not licensed at all. + + The precise terms and conditions for copying, distribution and +modification follow. + + GNU GENERAL PUBLIC LICENSE + TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION + + 0. This License applies to any program or other work which contains +a notice placed by the copyright holder saying it may be distributed +under the terms of this General Public License. The "Program", below, +refers to any such program or work, and a "work based on the Program" +means either the Program or any derivative work under copyright law: +that is to say, a work containing the Program or a portion of it, +either verbatim or with modifications and/or translated into another +language. (Hereinafter, translation is included without limitation in +the term "modification".) Each licensee is addressed as "you". + +Activities other than copying, distribution and modification are not +covered by this License; they are outside its scope. The act of +running the Program is not restricted, and the output from the Program +is covered only if its contents constitute a work based on the +Program (independent of having been made by running the Program). +Whether that is true depends on what the Program does. + + 1. You may copy and distribute verbatim copies of the Program's +source code as you receive it, in any medium, provided that you +conspicuously and appropriately publish on each copy an appropriate +copyright notice and disclaimer of warranty; keep intact all the +notices that refer to this License and to the absence of any warranty; +and give any other recipients of the Program a copy of this License +along with the Program. + +You may charge a fee for the physical act of transferring a copy, and +you may at your option offer warranty protection in exchange for a fee. + + 2. You may modify your copy or copies of the Program or any portion +of it, thus forming a work based on the Program, and copy and +distribute such modifications or work under the terms of Section 1 +above, provided that you also meet all of these conditions: + + a) You must cause the modified files to carry prominent notices + stating that you changed the files and the date of any change. + + b) You must cause any work that you distribute or publish, that in + whole or in part contains or is derived from the Program or any + part thereof, to be licensed as a whole at no charge to all third + parties under the terms of this License. + + c) If the modified program normally reads commands interactively + when run, you must cause it, when started running for such + interactive use in the most ordinary way, to print or display an + announcement including an appropriate copyright notice and a + notice that there is no warranty (or else, saying that you provide + a warranty) and that users may redistribute the program under + these conditions, and telling the user how to view a copy of this + License. (Exception: if the Program itself is interactive but + does not normally print such an announcement, your work based on + the Program is not required to print an announcement.) + +These requirements apply to the modified work as a whole. If +identifiable sections of that work are not derived from the Program, +and can be reasonably considered independent and separate works in +themselves, then this License, and its terms, do not apply to those +sections when you distribute them as separate works. But when you +distribute the same sections as part of a whole which is a work based +on the Program, the distribution of the whole must be on the terms of +this License, whose permissions for other licensees extend to the +entire whole, and thus to each and every part regardless of who wrote it. + +Thus, it is not the intent of this section to claim rights or contest +your rights to work written entirely by you; rather, the intent is to +exercise the right to control the distribution of derivative or +collective works based on the Program. + +In addition, mere aggregation of another work not based on the Program +with the Program (or with a work based on the Program) on a volume of +a storage or distribution medium does not bring the other work under +the scope of this License. + + 3. You may copy and distribute the Program (or a work based on it, +under Section 2) in object code or executable form under the terms of +Sections 1 and 2 above provided that you also do one of the following: + + a) Accompany it with the complete corresponding machine-readable + source code, which must be distributed under the terms of Sections + 1 and 2 above on a medium customarily used for software interchange; or, + + b) Accompany it with a written offer, valid for at least three + years, to give any third party, for a charge no more than your + cost of physically performing source distribution, a complete + machine-readable copy of the corresponding source code, to be + distributed under the terms of Sections 1 and 2 above on a medium + customarily used for software interchange; or, + + c) Accompany it with the information you received as to the offer + to distribute corresponding source code. (This alternative is + allowed only for noncommercial distribution and only if you + received the program in object code or executable form with such + an offer, in accord with Subsection b above.) + +The source code for a work means the preferred form of the work for +making modifications to it. For an executable work, complete source +code means all the source code for all modules it contains, plus any +associated interface definition files, plus the scripts used to +control compilation and installation of the executable. However, as a +special exception, the source code distributed need not include +anything that is normally distributed (in either source or binary +form) with the major components (compiler, kernel, and so on) of the +operating system on which the executable runs, unless that component +itself accompanies the executable. + +If distribution of executable or object code is made by offering +access to copy from a designated place, then offering equivalent +access to copy the source code from the same place counts as +distribution of the source code, even though third parties are not +compelled to copy the source along with the object code. + + 4. You may not copy, modify, sublicense, or distribute the Program +except as expressly provided under this License. Any attempt +otherwise to copy, modify, sublicense or distribute the Program is +void, and will automatically terminate your rights under this License. +However, parties who have received copies, or rights, from you under +this License will not have their licenses terminated so long as such +parties remain in full compliance. + + 5. You are not required to accept this License, since you have not +signed it. However, nothing else grants you permission to modify or +distribute the Program or its derivative works. These actions are +prohibited by law if you do not accept this License. Therefore, by +modifying or distributing the Program (or any work based on the +Program), you indicate your acceptance of this License to do so, and +all its terms and conditions for copying, distributing or modifying +the Program or works based on it. + + 6. Each time you redistribute the Program (or any work based on the +Program), the recipient automatically receives a license from the +original licensor to copy, distribute or modify the Program subject to +these terms and conditions. You may not impose any further +restrictions on the recipients' exercise of the rights granted herein. +You are not responsible for enforcing compliance by third parties to +this License. + + 7. If, as a consequence of a court judgment or allegation of patent +infringement or for any other reason (not limited to patent issues), +conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot +distribute so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you +may not distribute the Program at all. For example, if a patent +license would not permit royalty-free redistribution of the Program by +all those who receive copies directly or indirectly through you, then +the only way you could satisfy both it and this License would be to +refrain entirely from distribution of the Program. + +If any portion of this section is held invalid or unenforceable under +any particular circumstance, the balance of the section is intended to +apply and the section as a whole is intended to apply in other +circumstances. + +It is not the purpose of this section to induce you to infringe any +patents or other property right claims or to contest validity of any +such claims; this section has the sole purpose of protecting the +integrity of the free software distribution system, which is +implemented by public license practices. Many people have made +generous contributions to the wide range of software distributed +through that system in reliance on consistent application of that +system; it is up to the author/donor to decide if he or she is willing +to distribute software through any other system and a licensee cannot +impose that choice. + +This section is intended to make thoroughly clear what is believed to +be a consequence of the rest of this License. + + 8. If the distribution and/or use of the Program is restricted in +certain countries either by patents or by copyrighted interfaces, the +original copyright holder who places the Program under this License +may add an explicit geographical distribution limitation excluding +those countries, so that distribution is permitted only in or among +countries not thus excluded. In such case, this License incorporates +the limitation as if written in the body of this License. + + 9. The Free Software Foundation may publish revised and/or new versions +of the General Public License from time to time. Such new versions will +be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + +Each version is given a distinguishing version number. If the Program +specifies a version number of this License which applies to it and "any +later version", you have the option of following the terms and conditions +either of that version or of any later version published by the Free +Software Foundation. If the Program does not specify a version number of +this License, you may choose any version ever published by the Free Software +Foundation. + + 10. If you wish to incorporate parts of the Program into other free +programs whose distribution conditions are different, write to the author +to ask for permission. For software which is copyrighted by the Free +Software Foundation, write to the Free Software Foundation; we sometimes +make exceptions for this. Our decision will be guided by the two goals +of preserving the free status of all derivatives of our free software and +of promoting the sharing and reuse of software generally. + + NO WARRANTY + + 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY +FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN +OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES +PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED +OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF +MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS +TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE +PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, +REPAIR OR CORRECTION. + + 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR +REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, +INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING +OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED +TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY +YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER +PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE +POSSIBILITY OF SUCH DAMAGES. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +convey the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + {description} + Copyright (C) {year} {fullname} + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License along + with this program; if not, write to the Free Software Foundation, Inc., + 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + +Also add information on how to contact you by electronic and paper mail. + +If the program is interactive, make it output a short notice like this +when it starts in an interactive mode: + + Gnomovision version 69, Copyright (C) year name of author + Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it + under certain conditions; type `show c' for details. + +The hypothetical commands `show w' and `show c' should show the appropriate +parts of the General Public License. Of course, the commands you use may +be called something other than `show w' and `show c'; they could even be +mouse-clicks or menu items--whatever suits your program. + +You should also get your employer (if you work as a programmer) or your +school, if any, to sign a "copyright disclaimer" for the program, if +necessary. Here is a sample; alter the names: + + Yoyodyne, Inc., hereby disclaims all copyright interest in the program + `Gnomovision' (which makes passes at compilers) written by James Hacker. + + {signature of Ty Coon}, 1 April 1989 + Ty Coon, President of Vice + +This General Public License does not permit incorporating your program into +proprietary programs. If your program is a subroutine library, you may +consider it more useful to permit linking proprietary applications with the +library. If this is what you want to do, use the GNU Lesser General +Public License instead of this License. diff --git a/image-vectorize/plugin/vendor/potrace/Posterizer.js b/image-vectorize/plugin/vendor/potrace/Posterizer.js new file mode 100644 index 0000000..b7d0931 --- /dev/null +++ b/image-vectorize/plugin/vendor/potrace/Posterizer.js @@ -0,0 +1,458 @@ +'use strict'; + +var Potrace = require('./Potrace'); +var utils = require('./utils'); + +/** + * Takes multiple samples using {@link Potrace} with different threshold + * settings and combines output into a single file. + * + * @param {Posterizer~Options} [options] + * @constructor + */ +function Posterizer(options) { + this._potrace = new Potrace(); + + this._calculatedThreshold = null; + + this._params = { + threshold: Potrace.THRESHOLD_AUTO, + blackOnWhite: true, + steps: Posterizer.STEPS_AUTO, + background: Potrace.COLOR_TRANSPARENT, + fillStrategy: Posterizer.FILL_DOMINANT, + rangeDistribution: Posterizer.RANGES_AUTO + }; + + if (options) { + this.setParameters(options); + } +} + +// Inherit constants from Potrace class +for (var key in Potrace) { + if (Object.prototype.hasOwnProperty.call(Potrace, key) && key === key.toUpperCase()) { + Posterizer[key] = Potrace[key]; + } +} + +Posterizer.STEPS_AUTO = -1; +Posterizer.FILL_SPREAD = 'spread'; +Posterizer.FILL_DOMINANT = 'dominant'; +Posterizer.FILL_MEDIAN = 'median'; +Posterizer.FILL_MEAN = 'mean'; + +Posterizer.RANGES_AUTO = 'auto'; +Posterizer.RANGES_EQUAL = 'equal'; + +Posterizer.prototype = { + /** + * Fine tuning to color ranges. + * + * If last range (featuring most saturated color) is larger than 10% of color space (25 units) + * then we want to add another color stop, that hopefully will include darkest pixels, improving presence of + * shadows and line art + * + * @param ranges + * @private + */ + _addExtraColorStop: function(ranges) { + var blackOnWhite = this._params.blackOnWhite; + var lastColorStop = ranges[ranges.length - 1]; + var lastRangeFrom = blackOnWhite ? 0 : lastColorStop.value; + var lastRangeTo = blackOnWhite ? lastColorStop.value : 255; + + if (lastRangeTo - lastRangeFrom > 25 && lastColorStop.colorIntensity !== 1) { + var histogram = this._getImageHistogram(); + var levels = histogram.getStats(lastRangeFrom, lastRangeTo).levels; + + var newColorStop = levels.mean + levels.stdDev <= 25 ? levels.mean + levels.stdDev + : levels.mean - levels.stdDev <= 25 ? levels.mean - levels.stdDev + : 25; + + var newStats = (blackOnWhite ? histogram.getStats(0, newColorStop) : histogram.getStats(newColorStop, 255)); + var color = newStats.levels.mean; + + ranges.push({ + value: Math.abs((blackOnWhite ? 0 : 255) - newColorStop), + colorIntensity: isNaN(color) ? 0 : ((blackOnWhite ? 255 - color : color) / 255) + }); + } + + return ranges; + }, + + + /** + * Calculates color intensity for each element of numeric array + * + * @param {number[]} colorStops + * @returns {{ levels: number, colorIntensity: number }[]} + * @private + */ + _calcColorIntensity: function(colorStops) { + var blackOnWhite = this._params.blackOnWhite; + var colorSelectionStrat = this._params.fillStrategy; + var histogram = colorSelectionStrat !== Posterizer.FILL_SPREAD ? this._getImageHistogram() : null; + var fullRange = Math.abs(this._paramThreshold() - (blackOnWhite ? 0 : 255)); + + return colorStops.map(function(threshold, index) { + var nextValue = index + 1 === colorStops.length ? (blackOnWhite ? -1 : 256) : colorStops[index + 1]; + var rangeStart = Math.round(blackOnWhite ? nextValue + 1 : threshold); + var rangeEnd = Math.round(blackOnWhite ? threshold : nextValue - 1); + var factor = index / (colorStops.length - 1); + var intervalSize = rangeEnd - rangeStart; + var stats = histogram.getStats(rangeStart, rangeEnd); + var color = -1; + + if (stats.pixels === 0) { + return { + value: threshold, + colorIntensity: 0 + }; + } + + switch (colorSelectionStrat) { + case Posterizer.FILL_SPREAD: + // We want it to be 0 (255 when white on black) at the most saturated end, so... + color = (blackOnWhite ? rangeStart : rangeEnd) + + (blackOnWhite ? 1 : -1) * intervalSize * Math.max(0.5, fullRange / 255) * factor; + break; + case Posterizer.FILL_DOMINANT: + color = histogram.getDominantColor(rangeStart, rangeEnd, utils.clamp(intervalSize, 1, 5)); + break; + case Posterizer.FILL_MEAN: + color = stats.levels.mean; + break; + case Posterizer.FILL_MEDIAN: + color = stats.levels.median; + break; + } + + // We don't want colors to be too close to each other, so we introduce some spacing in between + if (index !== 0) { + color = blackOnWhite + ? utils.clamp(color, rangeStart, rangeEnd - Math.round(intervalSize * 0.1)) + : utils.clamp(color, rangeStart + Math.round(intervalSize * 0.1), rangeEnd); + } + + return { + value: threshold, + colorIntensity: color === -1 ? 0 : ((blackOnWhite ? 255 - color : color) / 255) + }; + }); + }, + + /** + * @returns {Histogram} + * @private + */ + _getImageHistogram: function() { + return this._potrace._luminanceData.histogram(); + }, + + /** + * Processes threshold, steps and rangeDistribution parameters and returns normalized array of color stops + * @returns {*} + * @private + */ + _getRanges: function() { + var steps = this._paramSteps(); + + if (!Array.isArray(steps)) { + return this._params.rangeDistribution === Posterizer.RANGES_AUTO + ? this._getRangesAuto() + : this._getRangesEquallyDistributed(); + } + + // Steps is array of thresholds and we want to preprocess it + + var colorStops = []; + var threshold = this._paramThreshold(); + var lookingForDarkPixels = this._params.blackOnWhite; + + steps.forEach(function(item) { + if (colorStops.indexOf(item) === -1 && utils.between(item, 0, 255)) { + colorStops.push(item); + } + }); + + if (!colorStops.length) { + colorStops.push(threshold); + } + + colorStops = colorStops.sort(function (a, b) { + return a < b === lookingForDarkPixels ? 1 : -1; + }); + + if (lookingForDarkPixels && colorStops[0] < threshold) { + colorStops.unshift(threshold); + } else if (!lookingForDarkPixels && colorStops[colorStops.length - 1] < threshold) { + colorStops.push(threshold); + } + + return this._calcColorIntensity(colorStops); + }, + + /** + * Calculates given (or lower) number of thresholds using automatic thresholding algorithm + * @returns {*} + * @private + */ + _getRangesAuto: function() { + var histogram = this._getImageHistogram(); + var steps = this._paramSteps(true); + var colorStops; + + if (this._params.threshold === Potrace.THRESHOLD_AUTO) { + colorStops = histogram.multilevelThresholding(steps); + } else { + var threshold = this._paramThreshold(); + + colorStops = this._params.blackOnWhite + ? histogram.multilevelThresholding(steps - 1, 0, threshold) + : histogram.multilevelThresholding(steps - 1, threshold, 255); + + if (this._params.blackOnWhite) { + colorStops.push(threshold); + } else { + colorStops.unshift(threshold); + } + } + + if (this._params.blackOnWhite) { + colorStops = colorStops.reverse(); + } + + return this._calcColorIntensity(colorStops); + }, + + /** + * Calculates color stops and color representing each segment, returning them + * from least to most intense color (black or white, depending on blackOnWhite parameter) + * + * @private + */ + _getRangesEquallyDistributed: function() { + var blackOnWhite = this._params.blackOnWhite; + var colorsToThreshold = blackOnWhite ? this._paramThreshold() : 255 - this._paramThreshold(); + var steps = this._paramSteps(); + + var stepSize = colorsToThreshold / steps; + var colorStops = []; + var i = steps - 1, + factor, + threshold; + + while (i >= 0) { + factor = i / (steps - 1); + threshold = Math.min(colorsToThreshold, (i + 1) * stepSize); + threshold = blackOnWhite ? threshold : 255 - threshold; + i--; + + colorStops.push(threshold); + } + + return this._calcColorIntensity(colorStops); + }, + + /** + * Returns valid steps value + * @param {Boolean} [count=false] + * @returns {number|number[]} + * @private + */ + _paramSteps: function(count) { + var steps = this._params.steps; + + if (Array.isArray(steps)) { + return count ? steps.length : steps; + } + + if (steps === Posterizer.STEPS_AUTO && this._params.threshold === Potrace.THRESHOLD_AUTO) { + return 4; + } + + var blackOnWhite = this._params.blackOnWhite; + var colorsCount = blackOnWhite ? this._paramThreshold() : 255 - this._paramThreshold(); + + return steps === Posterizer.STEPS_AUTO + ? (colorsCount > 200 ? 4 : 3) + : Math.min(colorsCount, Math.max(2, steps)); + }, + + /** + * Returns valid threshold value + * @returns {number} + * @private + */ + _paramThreshold: function() { + if (this._calculatedThreshold !== null) { + return this._calculatedThreshold; + } + + if (this._params.threshold !== Potrace.THRESHOLD_AUTO) { + this._calculatedThreshold = this._params.threshold; + return this._calculatedThreshold; + } + + var twoThresholds = this._getImageHistogram().multilevelThresholding(2); + this._calculatedThreshold = this._params.blackOnWhite ? twoThresholds[1] : twoThresholds[0]; + this._calculatedThreshold = this._calculatedThreshold || 128; + + return this._calculatedThreshold; + }, + + /** + * Running potrace on the image multiple times with different thresholds and returns an array + * of path tags + * + * @param {Boolean} [noFillColor] + * @returns {string[]} + * @private + */ + _pathTags: function(noFillColor) { + var ranges = this._getRanges(); + var potrace = this._potrace; + var blackOnWhite = this._params.blackOnWhite; + + if (ranges.length >= 10) { + ranges = this._addExtraColorStop(ranges); + } + + potrace.setParameters({ blackOnWhite: blackOnWhite }); + + var actualPrevLayersOpacity = 0; + + return ranges.map(function(colorStop) { + var thisLayerOpacity = colorStop.colorIntensity; + + if (thisLayerOpacity === 0) { + return ''; + } + + // NOTE: With big number of layers (something like 70) there will be noticeable math error on rendering side. + // In Chromium at least image will end up looking brighter overall compared to the same layers painted in solid colors. + // However it works fine with sane number of layers, and it's not like we can do much about it. + + var calculatedOpacity = (!actualPrevLayersOpacity || thisLayerOpacity === 1) + ? thisLayerOpacity + : ((actualPrevLayersOpacity - thisLayerOpacity) / (actualPrevLayersOpacity - 1)); + + calculatedOpacity = utils.clamp(parseFloat(calculatedOpacity.toFixed(3)), 0, 1); + actualPrevLayersOpacity = actualPrevLayersOpacity + (1 - actualPrevLayersOpacity) * calculatedOpacity; + + potrace.setParameters({ threshold: colorStop.value }); + + var element = noFillColor ? potrace.getPathTag('') : potrace.getPathTag(); + element = utils.setHtmlAttr(element, 'fill-opacity', calculatedOpacity.toFixed(3)); + + var canBeIgnored = calculatedOpacity === 0 || element.indexOf(' d=""') !== -1; + + // var c = Math.round(Math.abs((blackOnWhite ? 255 : 0) - 255 * thisLayerOpacity)); + // element = utils.setHtmlAttr(element, 'fill', 'rgb('+c+', '+c+', '+c+')'); + // element = utils.setHtmlAttr(element, 'fill-opacity', ''); + + return canBeIgnored ? '' : element; + }); + }, + + /** + * Loads image. + * + * @param {string|Buffer|Jimp} target Image source. Could be anything that {@link Jimp} can read (buffer, local path or url). Supported formats are: PNG, JPEG or BMP + * @param {Function} callback + */ + loadImage: function(target, callback) { + var self = this; + + this._potrace.loadImage(target, function(err) { + self._calculatedThreshold = null; + callback.call(self, err); + }); + }, + + /** + * 本项目新增:直接吃浏览器 ImageData(同步),与 Potrace#loadImageData 对应。 + * 灰度分层不需要异步读图 ⇒ 调用方拿到的就是同步结果,省掉一层回调。 + */ + loadImageData: function(imageData) { + this._potrace.loadImageData(imageData); + this._calculatedThreshold = null; + }, + + /** + * Sets parameters. Accepts same object as {Potrace} + * + * @param {Posterizer~Options} params + */ + setParameters: function(params) { + if (!params) { + return; + } + + this._potrace.setParameters(params); + + if (params.steps && !Array.isArray(params.steps) && (!utils.isNumber(params.steps) || !utils.between(params.steps, 1, 255))) { + throw new Error('Bad \'steps\' value'); + } + + for (var key in this._params) { + if (this._params.hasOwnProperty(key) && params.hasOwnProperty(key)) { + this._params[key] = params[key]; + } + } + + this._calculatedThreshold = null; + }, + + /** + * Returns image as tag. Always has viewBox specified + * + * @param {string} id + */ + getSymbol: function(id) { + var width = this._potrace._luminanceData.width; + var height = this._potrace._luminanceData.height; + var paths = this._pathTags(true); + + return '' + + paths.join('') + + ''; + }, + + /** + * Generates SVG image + * @returns {String} + */ + getSVG: function() { + var width = this._potrace._luminanceData.width, + height = this._potrace._luminanceData.height; + + var tags = this._pathTags(false); + + var svg = '\n\t' + + (this._params.background !== Potrace.COLOR_TRANSPARENT + ? '\n\t' + : '') + + tags.join('\n\t') + + '\n'; + + return svg.replace(/\n(?:\t*\n)+(\t*)/g, '\n$1'); + } +}; + +module.exports = Posterizer; + +/** + * Posterizer options + * + * @typedef {Potrace~Options} Posterizer~Options + * @property {Number} [steps] - Number of samples that needs to be taken (and number of layers in SVG). (default: Posterizer.STEPS_AUTO, which most likely will result in 3, sometimes 4) + * @property {*} [fillStrategy] - How to select fill color for color ranges - equally spread or dominant. (default: Posterizer.FILL_DOMINANT) + * @property {*} [rangeDistribution] - How to choose thresholds in-between - after equal intervals or automatically balanced. (default: Posterizer.RANGES_AUTO) + */ diff --git a/image-vectorize/plugin/vendor/potrace/Potrace.js b/image-vectorize/plugin/vendor/potrace/Potrace.js new file mode 100644 index 0000000..e064d4a --- /dev/null +++ b/image-vectorize/plugin/vendor/potrace/Potrace.js @@ -0,0 +1,1169 @@ +'use strict'; + +// ── 本项目内联改造(2026-11-05)──────────────────────────────────────────── +// 上游 npm 包 `potrace@2.1.8`(GPL-2.0,Peter Selinger 原算法的 JS 移植)用 jimp 读图, +// 浏览器里没有 jimp 也不需要它:插件本来就拿着 canvas 的 ImageData。 +// 改动只有两处:① 去掉 `require('jimp')`;② 新增 `loadImageData(imageData)`, +// 直接按 RGBA 算亮度(透明像素按白底合成,与原实现一致)。算法本体一行未动。 +// 许可:GPL-2.0,见同目录 LICENSE;插件产物为未混淆的可读源码,随分发一并提供。 +var Bitmap = require('./types/Bitmap'); +var Curve = require('./types/Curve'); +var Point = require('./types/Point'); +var Path = require('./types/Path'); +var Quad = require('./types/Quad'); +var Sum = require('./types/Sum'); +var Opti = require('./types/Opti'); + +var utils = require('./utils'); + +/** + * Potrace class + * + * @param {Potrace~Options} [options] + * @constructor + */ +function Potrace (options) { + this._luminanceData = null; + this._pathlist = []; + + this._imageLoadingIdentifier = null; + this._imageLoaded = false; + this._processed = false; + + this._params = { + turnPolicy: Potrace.TURNPOLICY_MINORITY, + turdSize: 2, + alphaMax: 1, + optCurve: true, + optTolerance: 0.2, + threshold: Potrace.THRESHOLD_AUTO, + blackOnWhite: true, + color: Potrace.COLOR_AUTO, + background: Potrace.COLOR_TRANSPARENT, + width: null, + height: null + }; + + if (options) { + this.setParameters(options); + } +} + +Potrace.COLOR_AUTO = 'auto'; +Potrace.COLOR_TRANSPARENT = 'transparent'; +Potrace.THRESHOLD_AUTO = -1; +Potrace.TURNPOLICY_BLACK = 'black'; +Potrace.TURNPOLICY_WHITE = 'white'; +Potrace.TURNPOLICY_LEFT = 'left'; +Potrace.TURNPOLICY_RIGHT = 'right'; +Potrace.TURNPOLICY_MINORITY = 'minority'; +Potrace.TURNPOLICY_MAJORITY = 'majority'; + +var SUPPORTED_TURNPOLICY_VALUES = [ + Potrace.TURNPOLICY_BLACK, Potrace.TURNPOLICY_WHITE, + Potrace.TURNPOLICY_LEFT, Potrace.TURNPOLICY_RIGHT, + Potrace.TURNPOLICY_MINORITY, Potrace.TURNPOLICY_MAJORITY +]; + +Potrace.prototype = { + /** + * Creating a new {@link Path} for every group of black pixels. + * @private + */ + _bmToPathlist: function() { + var self = this, + threshold = this._params.threshold, + blackOnWhite = this._params.blackOnWhite, + blackMap, + currentPoint = new Point(0, 0), + path; + + if (threshold === Potrace.THRESHOLD_AUTO) { + threshold = this._luminanceData.histogram().autoThreshold() || 128; + } + + blackMap = this._luminanceData.copy(function(lum) { + var pastTheThreshold = blackOnWhite + ? lum > threshold + : lum < threshold; + + return pastTheThreshold ? 0 : 1; + }); + + /** + * finds next black pixel of the image + * + * @param {Point} point + * @returns {boolean} + * @private + */ + function findNext(point) { + var i = blackMap.pointToIndex(point); + + while (i < blackMap.size && blackMap.data[i] !== 1) { + i++; + } + + return i < blackMap.size && blackMap.indexToPoint(i); + } + + function majority(x, y) { + var i, a, ct; + + for (i = 2; i < 5; i++) { + ct = 0; + for (a = -i + 1; a <= i - 1; a++) { + ct += blackMap.getValueAt(x + a, y + i - 1) ? 1 : -1; + ct += blackMap.getValueAt(x + i - 1, y + a - 1) ? 1 : -1; + ct += blackMap.getValueAt(x + a - 1, y - i) ? 1 : -1; + ct += blackMap.getValueAt(x - i, y + a) ? 1 : -1; + } + + if (ct > 0) { + return 1; + } else if (ct < 0) { + return 0; + } + } + return 0; + } + + function findPath(point) { + var path = new Path(), + x = point.x, + y = point.y, + dirx = 0, + diry = 1, + tmp; + + path.sign = blackMap.getValueAt(point.x, point.y) ? "+" : "-"; + + while (1) { + path.pt.push(new Point(x, y)); + if (x > path.maxX) + path.maxX = x; + if (x < path.minX) + path.minX = x; + if (y > path.maxY) + path.maxY = y; + if (y < path.minY) + path.minY = y; + path.len++; + + x += dirx; + y += diry; + path.area -= x * diry; + + if (x === point.x && y === point.y) + break; + + var l = blackMap.getValueAt(x + (dirx + diry - 1 ) / 2, y + (diry - dirx - 1) / 2); + var r = blackMap.getValueAt(x + (dirx - diry - 1) / 2, y + (diry + dirx - 1) / 2); + + if (r && !l) { + if (self._params.turnPolicy === "right" || + (self._params.turnPolicy === "black" && path.sign === '+') || + (self._params.turnPolicy === "white" && path.sign === '-') || + (self._params.turnPolicy === "majority" && majority(x, y)) || + (self._params.turnPolicy === "minority" && !majority(x, y))) { + tmp = dirx; + dirx = -diry; + diry = tmp; + } else { + tmp = dirx; + dirx = diry; + diry = -tmp; + } + } else if (r) { + tmp = dirx; + dirx = -diry; + diry = tmp; + } else if (!l) { + tmp = dirx; + dirx = diry; + diry = -tmp; + } + } + return path; + } + + function xorPath(path){ + var y1 = path.pt[0].y, + len = path.len, + x, y, maxX, minY, i, j, + indx; + + for (i = 1; i < len; i++) { + x = path.pt[i].x; + y = path.pt[i].y; + + if (y !== y1) { + minY = y1 < y ? y1 : y; + maxX = path.maxX; + for (j = x; j < maxX; j++) { + indx = blackMap.pointToIndex(j, minY); + blackMap.data[indx] = blackMap.data[indx] ? 0 : 1; + } + y1 = y; + } + } + } + + // Clear path list + this._pathlist = []; + + while (currentPoint = findNext(currentPoint)) { + path = findPath(currentPoint); + xorPath(path); + + if (path.area > self._params.turdSize) { + this._pathlist.push(path); + } + } + }, + + /** + * Processes path list created by _bmToPathlist method creating and optimizing {@link Curve}'s + * @private + */ + _processPath: function() { + var self = this; + + function calcSums(path) { + var i, x, y; + path.x0 = path.pt[0].x; + path.y0 = path.pt[0].y; + + path.sums = []; + var s = path.sums; + s.push(new Sum(0, 0, 0, 0, 0)); + for(i = 0; i < path.len; i++){ + x = path.pt[i].x - path.x0; + y = path.pt[i].y - path.y0; + s.push(new Sum(s[i].x + x, s[i].y + y, s[i].xy + x * y, + s[i].x2 + x * x, s[i].y2 + y * y)); + } + } + + function calcLon(path) { + + var n = path.len, + pt = path.pt, + dir, + pivk = new Array(n), + nc = new Array(n), + ct = new Array(4); + + path.lon = new Array(n); + + var constraint = [new Point(), new Point()], + cur = new Point(), + off = new Point(), + dk = new Point(), + foundk; + + var i, j, k1, a, b, c, d, k = 0; + for(i = n - 1; i >= 0; i--){ + if (pt[i].x != pt[k].x && pt[i].y != pt[k].y) { + k = i + 1; + } + nc[i] = k; + } + + for (i = n - 1; i >= 0; i--) { + ct[0] = ct[1] = ct[2] = ct[3] = 0; + dir = (3 + 3 * (pt[utils.mod(i + 1, n)].x - pt[i].x) + + (pt[utils.mod(i + 1, n)].y - pt[i].y)) / 2; + ct[dir]++; + + constraint[0].x = 0; + constraint[0].y = 0; + constraint[1].x = 0; + constraint[1].y = 0; + + k = nc[i]; + k1 = i; + while (1) { + foundk = 0; + dir = (3 + 3 * utils.sign(pt[k].x - pt[k1].x) + + utils.sign(pt[k].y - pt[k1].y)) / 2; + ct[dir]++; + + if (ct[0] && ct[1] && ct[2] && ct[3]) { + pivk[i] = k1; + foundk = 1; + break; + } + + cur.x = pt[k].x - pt[i].x; + cur.y = pt[k].y - pt[i].y; + + if (utils.xprod(constraint[0], cur) < 0 || utils.xprod(constraint[1], cur) > 0) { + break; + } + + if (Math.abs(cur.x) <= 1 && Math.abs(cur.y) <= 1) { + + } else { + off.x = cur.x + ((cur.y >= 0 && (cur.y > 0 || cur.x < 0)) ? 1 : -1); + off.y = cur.y + ((cur.x <= 0 && (cur.x < 0 || cur.y < 0)) ? 1 : -1); + if (utils.xprod(constraint[0], off) >= 0) { + constraint[0].x = off.x; + constraint[0].y = off.y; + } + off.x = cur.x + ((cur.y <= 0 && (cur.y < 0 || cur.x < 0)) ? 1 : -1); + off.y = cur.y + ((cur.x >= 0 && (cur.x > 0 || cur.y < 0)) ? 1 : -1); + if (utils.xprod(constraint[1], off) <= 0) { + constraint[1].x = off.x; + constraint[1].y = off.y; + } + } + k1 = k; + k = nc[k1]; + if (!utils.cyclic(k, i, k1)) { + break; + } + } + if (foundk === 0) { + dk.x = utils.sign(pt[k].x-pt[k1].x); + dk.y = utils.sign(pt[k].y-pt[k1].y); + cur.x = pt[k1].x - pt[i].x; + cur.y = pt[k1].y - pt[i].y; + + a = utils.xprod(constraint[0], cur); + b = utils.xprod(constraint[0], dk); + c = utils.xprod(constraint[1], cur); + d = utils.xprod(constraint[1], dk); + + j = 10000000; + + if (b < 0) { + j = Math.floor(a / -b); + } + if (d > 0) { + j = Math.min(j, Math.floor(-c / d)); + } + + pivk[i] = utils.mod(k1+j,n); + } + } + + j=pivk[n-1]; + path.lon[n-1]=j; + for (i=n-2; i>=0; i--) { + if (utils.cyclic(i+1,pivk[i],j)) { + j=pivk[i]; + } + path.lon[i]=j; + } + + for (i=n-1; utils.cyclic(utils.mod(i+1,n),j,path.lon[i]); i--) { + path.lon[i] = j; + } + } + + function bestPolygon(path) { + + function penalty3(path, i, j) { + + var n = path.len, pt = path.pt, sums = path.sums; + var x, y, xy, x2, y2, + k, a, b, c, s, + px, py, ex, ey, + r = 0; + if (j>=n) { + j -= n; + r = 1; + } + + if (r === 0) { + x = sums[j+1].x - sums[i].x; + y = sums[j+1].y - sums[i].y; + x2 = sums[j+1].x2 - sums[i].x2; + xy = sums[j+1].xy - sums[i].xy; + y2 = sums[j+1].y2 - sums[i].y2; + k = j+1 - i; + } else { + x = sums[j+1].x - sums[i].x + sums[n].x; + y = sums[j+1].y - sums[i].y + sums[n].y; + x2 = sums[j+1].x2 - sums[i].x2 + sums[n].x2; + xy = sums[j+1].xy - sums[i].xy + sums[n].xy; + y2 = sums[j+1].y2 - sums[i].y2 + sums[n].y2; + k = j+1 - i + n; + } + + px = (pt[i].x + pt[j].x) / 2.0 - pt[0].x; + py = (pt[i].y + pt[j].y) / 2.0 - pt[0].y; + ey = (pt[j].x - pt[i].x); + ex = -(pt[j].y - pt[i].y); + + a = ((x2 - 2*x*px) / k + px*px); + b = ((xy - x*py - y*px) / k + px*py); + c = ((y2 - 2*y*py) / k + py*py); + + s = ex*ex*a + 2*ex*ey*b + ey*ey*c; + + return Math.sqrt(s); + } + + var i, j, m, k, + n = path.len, + pen = new Array(n + 1), + prev = new Array(n + 1), + clip0 = new Array(n), + clip1 = new Array(n + 1), + seg0 = new Array (n + 1), + seg1 = new Array(n + 1), + thispen, best, c; + + for (i=0; i0; j--) { + seg1[j] = i; + i = clip1[i]; + } + seg1[0] = 0; + + pen[0]=0; + for (j=1; j<=m; j++) { + for (i=seg1[j]; i<=seg0[j]; i++) { + best = -1; + for (k=seg0[j-1]; k>=clip1[i]; k--) { + thispen = penalty3(path, k, i) + pen[k]; + if (best < 0 || thispen < best) { + prev[i] = k; + best = thispen; + } + } + pen[i] = best; + } + } + path.m = m; + path.po = new Array(m); + + for (i=n, j=m-1; i>0; j--) { + i = prev[i]; + path.po[j] = i; + } + } + + function adjustVertices(path) { + + function pointslope(path, i, j, ctr, dir) { + + var n = path.len, sums = path.sums, + x, y, x2, xy, y2, + k, a, b, c, lambda2, l, r=0; + + while (j>=n) { + j-=n; + r+=1; + } + while (i>=n) { + i-=n; + r-=1; + } + while (j<0) { + j+=n; + r-=1; + } + while (i<0) { + i+=n; + r+=1; + } + + x = sums[j+1].x-sums[i].x+r*sums[n].x; + y = sums[j+1].y-sums[i].y+r*sums[n].y; + x2 = sums[j+1].x2-sums[i].x2+r*sums[n].x2; + xy = sums[j+1].xy-sums[i].xy+r*sums[n].xy; + y2 = sums[j+1].y2-sums[i].y2+r*sums[n].y2; + k = j+1-i+r*n; + + ctr.x = x/k; + ctr.y = y/k; + + a = (x2-x*x/k)/k; + b = (xy-x*y/k)/k; + c = (y2-y*y/k)/k; + + lambda2 = (a+c+Math.sqrt((a-c)*(a-c)+4*b*b))/2; + + a -= lambda2; + c -= lambda2; + + if (Math.abs(a) >= Math.abs(c)) { + l = Math.sqrt(a*a+b*b); + if (l!==0) { + dir.x = -b/l; + dir.y = a/l; + } + } else { + l = Math.sqrt(c*c+b*b); + if (l!==0) { + dir.x = -c/l; + dir.y = b/l; + } + } + if (l===0) { + dir.x = dir.y = 0; + } + } + + var m = path.m, po = path.po, n = path.len, pt = path.pt, + x0 = path.x0, y0 = path.y0, + ctr = new Array(m), dir = new Array(m), + q = new Array(m), + v = new Array(3), d, i, j, k, l, + s = new Point(); + + path.curve = new Curve(m); + + for (i=0; iQ.at(1, 1)) { + v[0] = -Q.at(0, 1); + v[1] = Q.at(0, 0); + } else if (Q.at(1, 1)) { + v[0] = -Q.at(1, 1); + v[1] = Q.at(1, 0); + } else { + v[0] = 1; + v[1] = 0; + } + d = v[0] * v[0] + v[1] * v[1]; + v[2] = - v[1] * s.y - v[0] * s.x; + for (l=0; l<3; l++) { + for (k=0; k<3; k++) { + Q.data[l * 3 + k] += v[l] * v[k] / d; + } + } + } + dx = Math.abs(w.x-s.x); + dy = Math.abs(w.y-s.y); + if (dx <= 0.5 && dy <= 0.5) { + path.curve.vertex[i] = new Point(w.x+x0, w.y+y0); + continue; + } + + min = utils.quadform(Q, s); + xmin = s.x; + ymin = s.y; + + if (Q.at(0, 0) !== 0.0) { + for (z=0; z<2; z++) { + w.y = s.y-0.5+z; + w.x = - (Q.at(0, 1) * w.y + Q.at(0, 2)) / Q.at(0, 0); + dx = Math.abs(w.x-s.x); + cand = utils.quadform(Q, w); + if (dx <= 0.5 && cand < min) { + min = cand; + xmin = w.x; + ymin = w.y; + } + } + } + + if (Q.at(1, 1) !== 0.0) { + for (z=0; z<2; z++) { + w.x = s.x-0.5+z; + w.y = - (Q.at(1, 0) * w.x + Q.at(1, 2)) / Q.at(1, 1); + dy = Math.abs(w.y-s.y); + cand = utils.quadform(Q, w); + if (dy <= 0.5 && cand < min) { + min = cand; + xmin = w.x; + ymin = w.y; + } + } + } + + for (l=0; l<2; l++) { + for (k=0; k<2; k++) { + w.x = s.x-0.5+l; + w.y = s.y-0.5+k; + cand = utils.quadform(Q, w); + if (cand < min) { + min = cand; + xmin = w.x; + ymin = w.y; + } + } + } + + path.curve.vertex[i] = new Point(xmin + x0, ymin + y0); + } + } + + function reverse(path) { + var curve = path.curve, m = curve.n, v = curve.vertex, i, j, tmp; + + for (i=0, j=m-1; i1 ? (1 - 1.0/dd) : 0; + alpha = alpha / 0.75; + } else { + alpha = 4/3.0; + } + curve.alpha0[j] = alpha; + + if (alpha >= self._params.alphaMax) { + curve.tag[j] = "CORNER"; + curve.c[3 * j + 1] = curve.vertex[j]; + curve.c[3 * j + 2] = p4; + } else { + if (alpha < 0.55) { + alpha = 0.55; + } else if (alpha > 1) { + alpha = 1; + } + p2 = utils.interval(0.5+0.5*alpha, curve.vertex[i], curve.vertex[j]); + p3 = utils.interval(0.5+0.5*alpha, curve.vertex[k], curve.vertex[j]); + curve.tag[j] = "CURVE"; + curve.c[3 * j + 0] = p2; + curve.c[3 * j + 1] = p3; + curve.c[3 * j + 2] = p4; + } + curve.alpha[j] = alpha; + curve.beta[j] = 0.5; + } + curve.alphaCurve = 1; + } + + function optiCurve(path) { + + function opti_penalty(path, i, j, res, opttolerance, convc, areac) { + var m = path.curve.n, curve = path.curve, vertex = curve.vertex, + k, k1, k2, conv, i1, + area, alpha, d, d1, d2, + p0, p1, p2, p3, pt, + A, R, A1, A2, A3, A4, + s, t; + + if (i==j) { + return 1; + } + + k = i; + i1 = utils.mod(i+1, m); + k1 = utils.mod(k+1, m); + conv = convc[k1]; + if (conv === 0) { + return 1; + } + d = utils.ddist(vertex[i], vertex[i1]); + for (k=k1; k!=j; k=k1) { + k1 = utils.mod(k+1, m); + k2 = utils.mod(k+2, m); + if (convc[k1] != conv) { + return 1; + } + if (utils.sign(utils.cprod(vertex[i], vertex[i1], vertex[k1], vertex[k2])) != + conv) { + return 1; + } + if (utils.iprod1(vertex[i], vertex[i1], vertex[k1], vertex[k2]) < + d * utils.ddist(vertex[k1], vertex[k2]) * -0.999847695156) { + return 1; + } + } + + p0 = curve.c[utils.mod(i,m) * 3 + 2].copy(); + p1 = vertex[utils.mod(i+1,m)].copy(); + p2 = vertex[utils.mod(j,m)].copy(); + p3 = curve.c[utils.mod(j,m) * 3 + 2].copy(); + + area = areac[j] - areac[i]; + area -= utils.dpara(vertex[0], curve.c[i * 3 + 2], curve.c[j * 3 + 2])/2; + if (i>=j) { + area += areac[m]; + } + + A1 = utils.dpara(p0, p1, p2); + A2 = utils.dpara(p0, p1, p3); + A3 = utils.dpara(p0, p2, p3); + + A4 = A1+A3-A2; + + if (A2 == A1) { + return 1; + } + + t = A3/(A3-A4); + s = A2/(A2-A1); + A = A2 * t / 2.0; + + if (A === 0.0) { + return 1; + } + + R = area / A; + alpha = 2 - Math.sqrt(4 - R / 0.3); + + res.c[0] = utils.interval(t * alpha, p0, p1); + res.c[1] = utils.interval(s * alpha, p3, p2); + res.alpha = alpha; + res.t = t; + res.s = s; + + p1 = res.c[0].copy(); + p2 = res.c[1].copy(); + + res.pen = 0; + + for (k=utils.mod(i+1,m); k!=j; k=k1) { + k1 = utils.mod(k+1,m); + t = utils.tangent(p0, p1, p2, p3, vertex[k], vertex[k1]); + if (t<-0.5) { + return 1; + } + pt = utils.bezier(t, p0, p1, p2, p3); + d = utils.ddist(vertex[k], vertex[k1]); + if (d === 0.0) { + return 1; + } + d1 = utils.dpara(vertex[k], vertex[k1], pt) / d; + if (Math.abs(d1) > opttolerance) { + return 1; + } + if (utils.iprod(vertex[k], vertex[k1], pt) < 0 || + utils.iprod(vertex[k1], vertex[k], pt) < 0) { + return 1; + } + res.pen += d1 * d1; + } + + for (k=i; k!=j; k=k1) { + k1 = utils.mod(k+1,m); + t = utils.tangent(p0, p1, p2, p3, curve.c[k * 3 + 2], curve.c[k1 * 3 + 2]); + if (t<-0.5) { + return 1; + } + pt = utils.bezier(t, p0, p1, p2, p3); + d = utils.ddist(curve.c[k * 3 + 2], curve.c[k1 * 3 + 2]); + if (d === 0.0) { + return 1; + } + d1 = utils.dpara(curve.c[k * 3 + 2], curve.c[k1 * 3 + 2], pt) / d; + d2 = utils.dpara(curve.c[k * 3 + 2], curve.c[k1 * 3 + 2], vertex[k1]) / d; + d2 *= 0.75 * curve.alpha[k1]; + if (d2 < 0) { + d1 = -d1; + d2 = -d2; + } + if (d1 < d2 - opttolerance) { + return 1; + } + if (d1 < d2) { + res.pen += (d1 - d2) * (d1 - d2); + } + } + + return 0; + } + + var curve = path.curve, m = curve.n, vert = curve.vertex, + pt = new Array(m + 1), + pen = new Array(m + 1), + len = new Array(m + 1), + opt = new Array(m + 1), + om, i,j,r, + o = new Opti(), p0, + i1, area, alpha, ocurve, + s, t; + + var convc = new Array(m), areac = new Array(m + 1); + + for (i=0; i=0; i--) { + r = opti_penalty(path, i, utils.mod(j,m), o, self._params.optTolerance, convc, + areac); + if (r) { + break; + } + if (len[j] > len[i]+1 || + (len[j] == len[i]+1 && pen[j] > pen[i] + o.pen)) { + pt[j] = i; + pen[j] = pen[i] + o.pen; + len[j] = len[i] + 1; + opt[j] = o; + o = new Opti(); + } + } + } + om = len[m]; + ocurve = new Curve(om); + s = new Array(om); + t = new Array(om); + + j = m; + for (i=om-1; i>=0; i--) { + if (pt[j]==j-1) { + ocurve.tag[i] = curve.tag[utils.mod(j,m)]; + ocurve.c[i * 3 + 0] = curve.c[utils.mod(j,m) * 3 + 0]; + ocurve.c[i * 3 + 1] = curve.c[utils.mod(j,m) * 3 + 1]; + ocurve.c[i * 3 + 2] = curve.c[utils.mod(j,m) * 3 + 2]; + ocurve.vertex[i] = curve.vertex[utils.mod(j,m)]; + ocurve.alpha[i] = curve.alpha[utils.mod(j,m)]; + ocurve.alpha0[i] = curve.alpha0[utils.mod(j,m)]; + ocurve.beta[i] = curve.beta[utils.mod(j,m)]; + s[i] = t[i] = 1.0; + } else { + ocurve.tag[i] = "CURVE"; + ocurve.c[i * 3 + 0] = opt[j].c[0]; + ocurve.c[i * 3 + 1] = opt[j].c[1]; + ocurve.c[i * 3 + 2] = curve.c[utils.mod(j,m) * 3 + 2]; + ocurve.vertex[i] = utils.interval(opt[j].s, curve.c[utils.mod(j,m) * 3 + 2], + vert[utils.mod(j,m)]); + ocurve.alpha[i] = opt[j].alpha; + ocurve.alpha0[i] = opt[j].alpha; + s[i] = opt[j].s; + t[i] = opt[j].t; + } + j = pt[j]; + } + + for (i=0; i tag without rest of the SVG file + * + * @param {String} [fillColor] - overrides color from parameters + * @returns {String} + */ + getPathTag: function(fillColor, scale) { + fillColor = arguments.length === 0 ? this._params.color : fillColor; + + if (fillColor === Potrace.COLOR_AUTO) { + fillColor = this._params.blackOnWhite ? 'black' : 'white'; + } + + if (!this._imageLoaded) { + throw new Error('Image should be loaded first'); + } + + if (!this._processed) { + this._bmToPathlist(); + this._processPath(); + this._processed = true; + } + + var tag = ''; + + return tag; + }, + + /** + * Returns tag. Always has viewBox specified and comes with no fill color, + * so it could be changed with tag + * + * @param id + * @returns {string} + */ + getSymbol: function(id) { + return '' + + this.getPathTag('') + + ''; + }, + + /** + * Generates SVG image + * @returns {String} + */ + getSVG: function() { + var width = this._params.width || this._luminanceData.width; + var height = this._params.height || this._luminanceData.height; + var scale = { + x: this._params.width ? this._params.width / this._luminanceData.width : 1, + y: this._params.height ? this._params.height / this._luminanceData.height : 1, + }; + + return '\n'+ + (this._params.background !== Potrace.COLOR_TRANSPARENT + ? '\t\n' + : '') + + '\t' + this.getPathTag(this._params.color, scale) + '\n' + + ''; + } +}; + +module.exports = Potrace; + +/** + * Potrace options + * + * @typedef {Object} Potrace~Options + * @property {*} [turnPolicy] - how to resolve ambiguities in path decomposition (default Potrace.TURNPOLICY_MINORITY) + * @property {Number} [turdSize] - suppress speckles of up to this size (default 2) + * @property {Number} [alphaMax] - corner threshold parameter (default 1) + * @property {Boolean} [optCurve] - curve optimization (default true) + * @property {Number} [optTolerance] - curve optimization tolerance (default 0.2) + * @property {Number} [threshold] - threshold below which color is considered black (0..255, default Potrace.THRESHOLD_AUTO) + * @property {Boolean} [blackOnWhite] - specifies colors by which side from threshold should be traced (default true) + * @property {string} [color] - foreground color (default: 'auto' (black or white)) Will be ignored when exporting as + * @property {string} [background] - background color (default: 'transparent') Will be ignored when exporting as + */ + +/** + * Jimp module + * @external Jimp + * @see https://www.npmjs.com/package/jimp + */ \ No newline at end of file diff --git a/image-vectorize/plugin/vendor/potrace/types/Bitmap.js b/image-vectorize/plugin/vendor/potrace/types/Bitmap.js new file mode 100644 index 0000000..5d5a099 --- /dev/null +++ b/image-vectorize/plugin/vendor/potrace/types/Bitmap.js @@ -0,0 +1,111 @@ +'use strict'; + +var Point = require('./Point'); +var utils = require('../utils'); +var Histogram; + +/** + * Represents a bitmap where each pixel can be a number in range of 0..255 + * Used internally to store luminance data. + * + * @param {Number} w + * @param {Number} h + * @constructor + */ +function Bitmap(w, h) { + this._histogram = null; + + this.width = w; + this.height = h; + this.size = w * h; + this.arrayBuffer = new ArrayBuffer(this.size); + this.data = new Uint8Array(this.arrayBuffer); +} + +module.exports = Bitmap; +Histogram = require('./Histogram'); + +Bitmap.prototype = { + /** + * Returns pixel value + * + * @param {Number|Point} x - index, point or x + * @param {Number} [y] + */ + getValueAt: function(x, y) { + var index = (typeof x === 'number' && typeof y !== 'number') ? x : this.pointToIndex(x, y); + return this.data[index]; + }, + + /** + * Converts {@link Point} to index value + * + * @param {Number} index + * @returns {Point} + */ + indexToPoint: function(index) { + var point = new Point(); + + if (utils.between(index, 0, this.size)) { + point.y = Math.floor(index / this.width); + point.x = index - point.y * this.width; + } else { + point.x = -1; + point.y = -1; + } + + return point; + }, + + /** + * Calculates index for point or coordinate pair + * + * @param {Number|Point} pointOrX + * @param {Number} [y] + * @returns {Number} + */ + pointToIndex: function(pointOrX, y) { + var _x = pointOrX, + _y = y; + + if (pointOrX instanceof Point) { + _x = pointOrX.x; + _y = pointOrX.y; + } + + if (!utils.between(_x, 0, this.width) || !utils.between(_y, 0, this.height)) { + return -1; + } + + return this.width * _y + _x; + }, + + /** + * Makes a copy of current bitmap + * + * @param {Function} [iterator] optional callback, used for processing pixel value. Accepted arguments: value, index + * @returns {Bitmap} + */ + copy: function(iterator) { + var bm = new Bitmap(this.width, this.height), + iteratorPresent = typeof iterator === 'function', + i; + + for (i = 0; i < this.size; i++) { + bm.data[i] = iteratorPresent ? iterator(this.data[i], i) : this.data[i]; + } + + return bm; + }, + + histogram: function() { + var Histogram = require('./Histogram'); + + if (this._histogram) { + return this._histogram; + } + + this._histogram = new Histogram(this); + return this._histogram; + } +}; \ No newline at end of file diff --git a/image-vectorize/plugin/vendor/potrace/types/Curve.js b/image-vectorize/plugin/vendor/potrace/types/Curve.js new file mode 100644 index 0000000..558f84c --- /dev/null +++ b/image-vectorize/plugin/vendor/potrace/types/Curve.js @@ -0,0 +1,21 @@ +'use strict'; + +/** + * Curve type + * + * @param n + * @constructor + * @protected + */ +function Curve(n) { + this.n = n; + this.tag = new Array(n); + this.c = new Array(n * 3); + this.alphaCurve = 0; + this.vertex = new Array(n); + this.alpha = new Array(n); + this.alpha0 = new Array(n); + this.beta = new Array(n); +} + +module.exports = Curve; \ No newline at end of file diff --git a/image-vectorize/plugin/vendor/potrace/types/Histogram.js b/image-vectorize/plugin/vendor/potrace/types/Histogram.js new file mode 100644 index 0000000..7158bee --- /dev/null +++ b/image-vectorize/plugin/vendor/potrace/types/Histogram.js @@ -0,0 +1,425 @@ +"use strict"; + +// Histogram + +var utils = require('../utils'); +var Jimp = null; try { Jimp = require('jimp'); } catch(e) {} +var Bitmap = require('./Bitmap'); + +var COLOR_DEPTH = 256; +var COLOR_RANGE_END = COLOR_DEPTH - 1; + +/** + * Calculates array index for pair of indexes. We multiple column (x) by 256 and then add row to it, + * this way `(index(i, j) + 1) === index(i, j + i)` thus we can reuse `index(i, j)` we once calculated + * + * Note: this is different from how indexes calculated in {@link Bitmap} class, keep it in mind. + * + * @param x + * @param y + * @returns {*} + * @private + */ +function index(x, y) { + return COLOR_DEPTH * x + y; +} + +function normalizeMinMax(levelMin, levelMax) { + /** + * Shared parameter normalization for methods 'multilevelThresholding', 'autoThreshold', 'getDominantColor' and 'getStats' + * + * @param levelMin + * @param levelMax + * @returns {number[]} + * @private + */ + levelMin = typeof levelMin === 'number' ? utils.clamp(Math.round(levelMin), 0, COLOR_RANGE_END) : 0; + levelMax = typeof levelMax === 'number' ? utils.clamp(Math.round(levelMax), 0, COLOR_RANGE_END) : COLOR_RANGE_END; + + if (levelMin > levelMax) { + throw new Error('Invalid range "'+ levelMin + '...' + levelMax + '"'); + } + + return [levelMin, levelMax]; +} + +/** + * 1D Histogram + * + * @param {Number|Bitmap|Jimp} imageSource - Image to collect pixel data from. Or integer to create empty histogram for image of specific size + * @param [mode] Used only for Jimp images. {@link Bitmap} currently can only store 256 values per pixel, so it's assumed that it contains values we are looking for + * @constructor + * @protected + */ +function Histogram(imageSource, mode) { + this.data = null; + this.pixels = 0; + this._sortedIndexes = null; + this._cachedStats = {}; + this._lookupTableH = null; + + if (typeof imageSource === 'number') { + this._createArray(imageSource); + } else if (imageSource instanceof Bitmap) { + this._collectValuesBitmap(imageSource); + } else if (Jimp && imageSource instanceof Jimp) { + this._collectValuesJimp(imageSource, mode); + } else { + throw new Error('Unsupported image source'); + } +} + +Histogram.MODE_LUMINANCE = 'luminance'; +Histogram.MODE_R = 'r'; +Histogram.MODE_G = 'g'; +Histogram.MODE_B = 'b'; + +Histogram.prototype = { + /** + * Initializes data array for an image of given pixel size + * @param imageSize + * @returns {Uint8Array|Uint16Array|Uint32Array} + * @private + */ + _createArray: function(imageSize) { + var ArrayType = imageSize <= Math.pow(2, 8) ? Uint8Array + : imageSize <= Math.pow(2, 16) ? Uint16Array : Uint32Array; + + this.pixels = imageSize; + + return this.data = new ArrayType(COLOR_DEPTH); + }, + + /** + * Aggregates color data from {@link Jimp} instance + * @param {Jimp} source + * @param mode + * @private + */ + _collectValuesJimp: function(source, mode) { + var pixelData = source.bitmap.data; + var data = this._createArray(source.bitmap.width * source.bitmap.height); + + source.scan(0, 0, source.bitmap.width, source.bitmap.height, function(x, y, idx) { + var val = mode === Histogram.MODE_R ? pixelData[idx] + : mode === Histogram.MODE_G ? pixelData[idx + 1] + : mode === Histogram.MODE_B ? pixelData[idx + 2] + : utils.luminance(pixelData[idx], pixelData[idx + 1], pixelData[idx + 2]); + + data[val]++; + }); + }, + + /** + * Aggregates color data from {@link Bitmap} instance + * @param {Bitmap} source + * @private + */ + _collectValuesBitmap: function(source) { + var data = this._createArray(source.size); + var len = source.data.length; + var color; + + for (var i = 0; i < len; i++) { + color = source.data[i]; + data[color]++ + } + }, + + /** + * Returns array of color indexes in ascending order + * @param refresh + * @returns {*} + * @private + */ + _getSortedIndexes: function(refresh) { + if (!refresh && this._sortedIndexes) { + return this._sortedIndexes; + } + + var data = this.data; + var indexes = new Array(COLOR_DEPTH); + var i = 0; + + for (i; i < COLOR_DEPTH; i++) { + indexes[i] = i; + } + + indexes.sort(function(a, b) { + return data[a] > data[b] ? 1 : data[a] < data[b] ? -1 : 0; + }); + + this._sortedIndexes = indexes; + return indexes; + }, + + /** + * Builds lookup table H from lookup tables P and S. + * see {@link http://www.iis.sinica.edu.tw/page/jise/2001/200109_01.pdf|this paper} for more details + * + * @returns {Float64Array} + * @private + */ + _thresholdingBuildLookupTable: function() { + var P = new Float64Array(COLOR_DEPTH * COLOR_DEPTH); + var S = new Float64Array(COLOR_DEPTH * COLOR_DEPTH); + var H = new Float64Array(COLOR_DEPTH * COLOR_DEPTH); + var pixelsTotal = this.pixels; + var i, j, idx, tmp; + + // diagonal + for (i = 1; i < COLOR_DEPTH; ++i) { + idx = index(i, i); + tmp = this.data[i] / pixelsTotal; + + P[idx] = tmp; + S[idx] = i * tmp; + } + + // calculate first row (row 0 is all zero) + for (i = 1; i < COLOR_DEPTH - 1; ++i) { + tmp = this.data[i + 1] / pixelsTotal; + idx = index(1, i); + + P[idx+1] = P[idx] + tmp; + S[idx+1] = S[idx] + (i + 1) * tmp; + } + + // using row 1 to calculate others + for (i = 2; i < COLOR_DEPTH; i++) { + for (j=i+1; j < COLOR_DEPTH; j++) { + P[index(i, j)] = P[index(1, j)] - P[index(1, i-1)]; + S[index(i, j)] = S[index(1, j)] - S[index(1, i-1)]; + } + } + + // now calculate H[i][j] + for (i = 1; i < COLOR_DEPTH; ++i) { + for (j = i + 1; j < COLOR_DEPTH; j++) { + idx = index(i, j); + H[idx] = P[idx] !== 0 ? S[idx] * S[idx] / P[idx] : 0; + } + } + + return this._lookupTableH = H; + }, + + /** + * Implements Algorithm For Multilevel Thresholding + * Receives desired number of color stops, returns array of said size. Could be limited to a range levelMin..levelMax + * + * Regardless of levelMin and levelMax values it still relies on between class variances for the entire histogram + * + * @param amount - how many thresholds should be calculated + * @param [levelMin=0] - histogram segment start + * @param [levelMax=255] - histogram segment end + * @returns {number[]} + */ + multilevelThresholding: function (amount, levelMin, levelMax) { + levelMin = normalizeMinMax(levelMin, levelMax); + levelMax = levelMin[1]; + levelMin = levelMin[0]; + amount = Math.min(levelMax - levelMin - 2, ~~amount); + + if (amount < 1) { + return []; + } + + if (!this._lookupTableH) { + this._thresholdingBuildLookupTable(); + } + + var H = this._lookupTableH; + + var colorStops = null; + var maxSig = 0; + + if (amount > 4) { + console.log('[Warning]: Threshold computation for more than 5 levels may take a long time'); + } + + function iterateRecursive (startingPoint, prevVariance, indexes, previousDepth) { + startingPoint = (startingPoint || 0) + 1; + prevVariance = prevVariance || 0; + indexes = indexes || (new Array(amount)); + previousDepth = previousDepth || 0; + + var depth = previousDepth + 1; // t + var variance; + + for (var i = startingPoint; i < levelMax - amount + previousDepth; i++) { + variance = prevVariance + H[index(startingPoint, i)]; + indexes[depth - 1] = i; + + if (depth + 1 < amount + 1) { + // we need to go deeper + iterateRecursive(i, variance, indexes, depth); + } else { + // enough, we can compare values now + variance += H[index(i + 1, levelMax)]; + + if (maxSig < variance) { + maxSig = variance; + colorStops = indexes.slice(); + } + } + } + } + + iterateRecursive(levelMin || 0); + + return colorStops ? colorStops : []; + }, + + /** + * Automatically finds threshold value using Algorithm For Multilevel Thresholding + * + * @param {number} [levelMin] + * @param {number} [levelMax] + * @returns {null|number} + */ + autoThreshold: function(levelMin, levelMax) { + var value = this.multilevelThresholding(1, levelMin, levelMax); + return value.length ? value[0] : null; + }, + + /** + * Returns dominant color in given range. Returns -1 if not a single color from the range present on the image + * + * @param [levelMin=0] + * @param [levelMax=255] + * @param [tolerance=1] + * @returns {number} + */ + getDominantColor: function(levelMin, levelMax, tolerance) { + levelMin = normalizeMinMax(levelMin, levelMax); + levelMax = levelMin[1]; + levelMin = levelMin[0]; + tolerance = tolerance || 1; + + var colors = this.data, + dominantIndex = -1, + dominantValue = -1, + i, j, tmp; + + if (levelMin === levelMax) { + return colors[levelMin] ? levelMin : -1; + } + + for (i=levelMin; i <= levelMax; i++) { + tmp = 0; + + for (j = ~~(tolerance / -2); j < tolerance; j++) { + tmp += utils.between(i + j, 0, COLOR_RANGE_END) ? colors[i + j] : 0; + } + + var summIsBigger = tmp > dominantValue; + var summEqualButMainColorIsBigger = dominantValue === tmp && (dominantIndex < 0 || colors[i] > colors[dominantIndex]); + + if (summIsBigger || summEqualButMainColorIsBigger) { + dominantIndex = i; + dominantValue = tmp; + } + } + + return dominantValue <= 0 ? -1 : dominantIndex; + }, + + /** + * Returns stats for histogram or its segment. + * + * Returned object contains median, mean and standard deviation for pixel values; + * peak, mean and median number of pixels per level and few other values + * + * If no pixels colors from specified range present on the image - most values will be NaN + * + * @param {Number} [levelMin=0] - histogram segment start + * @param {Number} [levelMax=255] - histogram segment end + * @param {Boolean} [refresh=false] - if cached result can be returned + * @returns {{levels: {mean: (number|*), median: *, stdDev: number, unique: number}, pixelsPerLevel: {mean: (number|*), median: (number|*), peak: number}, pixels: number}} + */ + getStats: function(levelMin, levelMax, refresh) { + levelMin = normalizeMinMax(levelMin, levelMax); + levelMax = levelMin[1]; + levelMin = levelMin[0]; + + if (!refresh && this._cachedStats[levelMin + '-' + levelMax]) { + return this._cachedStats[levelMin + '-' + levelMax]; + } + + var data = this.data; + var sortedIndexes = this._getSortedIndexes(); + + var pixelsTotal = 0; + var medianValue = null; + var meanValue; + var medianPixelIndex; + var pixelsPerLevelMean; + var pixelsPerLevelMedian; + var tmpSumOfDeviations = 0; + var tmpPixelsIterated = 0; + var allPixelValuesCombined = 0; + var i, tmpPixels, tmpPixelValue; + + var uniqueValues = 0; // counter for levels that's represented by at least one pixel + var mostPixelsPerLevel = 0; + + // Finding number of pixels and mean + + for (i = levelMin; i <= levelMax; i++) { + pixelsTotal += data[i]; + allPixelValuesCombined += data[i] * i; + + uniqueValues += data[i] === 0 ? 0 : 1; + + if (mostPixelsPerLevel < data[i]) { + mostPixelsPerLevel = data[i]; + } + } + + meanValue = allPixelValuesCombined / pixelsTotal; + pixelsPerLevelMean = pixelsTotal / (levelMax - levelMin); + pixelsPerLevelMedian = pixelsTotal / uniqueValues; + medianPixelIndex = Math.floor(pixelsTotal / 2); + + // Finding median and standard deviation + + for (i = 0; i < COLOR_DEPTH; i++) { + tmpPixelValue = sortedIndexes[i]; + tmpPixels = data[tmpPixelValue]; + + if (tmpPixelValue < levelMin || tmpPixelValue > levelMax) { + continue; + } + + tmpPixelsIterated += tmpPixels; + tmpSumOfDeviations += Math.pow(tmpPixelValue - meanValue, 2) * tmpPixels; + + if (medianValue === null && tmpPixelsIterated >= medianPixelIndex) { + medianValue = tmpPixelValue; + } + } + + return this._cachedStats[levelMin + '-' + levelMax] = { + // various pixel counts for levels (0..255) + + levels: { + mean: meanValue, + median: medianValue, + stdDev: Math.sqrt(tmpSumOfDeviations / pixelsTotal), + unique: uniqueValues + }, + + // what's visually represented as bars + pixelsPerLevel: { + mean: pixelsPerLevelMean, + median: pixelsPerLevelMedian, + peak: mostPixelsPerLevel + }, + + pixels: pixelsTotal + }; + } +}; + +module.exports = Histogram; \ No newline at end of file diff --git a/image-vectorize/plugin/vendor/potrace/types/Opti.js b/image-vectorize/plugin/vendor/potrace/types/Opti.js new file mode 100644 index 0000000..1b2a45f --- /dev/null +++ b/image-vectorize/plugin/vendor/potrace/types/Opti.js @@ -0,0 +1,13 @@ +'use strict'; + +var Point = require('./Point'); + +function Opti() { + this.pen = 0; + this.c = [new Point(), new Point()]; + this.t = 0; + this.s = 0; + this.alpha = 0; +} + +module.exports = Opti; \ No newline at end of file diff --git a/image-vectorize/plugin/vendor/potrace/types/Path.js b/image-vectorize/plugin/vendor/potrace/types/Path.js new file mode 100644 index 0000000..cb0662c --- /dev/null +++ b/image-vectorize/plugin/vendor/potrace/types/Path.js @@ -0,0 +1,14 @@ +'use strict'; + +function Path() { + this.area = 0; + this.len = 0; + this.curve = {}; + this.pt = []; + this.minX = 100000; + this.minY = 100000; + this.maxX = -1; + this.maxY = -1; +} + +module.exports = Path; \ No newline at end of file diff --git a/image-vectorize/plugin/vendor/potrace/types/Point.js b/image-vectorize/plugin/vendor/potrace/types/Point.js new file mode 100644 index 0000000..458dca0 --- /dev/null +++ b/image-vectorize/plugin/vendor/potrace/types/Point.js @@ -0,0 +1,14 @@ +'use strict'; + +function Point(x, y) { + this.x = x || 0; + this.y = y || 0; +} + +Point.prototype = { + copy: function() { + return new Point(this.x, this.y); + } +}; + +module.exports = Point; \ No newline at end of file diff --git a/image-vectorize/plugin/vendor/potrace/types/Quad.js b/image-vectorize/plugin/vendor/potrace/types/Quad.js new file mode 100644 index 0000000..0df71f8 --- /dev/null +++ b/image-vectorize/plugin/vendor/potrace/types/Quad.js @@ -0,0 +1,11 @@ +'use strict'; + +function Quad() { + this.data = [0,0,0,0,0,0,0,0,0]; +} + +Quad.prototype.at = function(x, y) { + return this.data[x * 3 + y]; +}; + +module.exports = Quad; \ No newline at end of file diff --git a/image-vectorize/plugin/vendor/potrace/types/Sum.js b/image-vectorize/plugin/vendor/potrace/types/Sum.js new file mode 100644 index 0000000..bbc5356 --- /dev/null +++ b/image-vectorize/plugin/vendor/potrace/types/Sum.js @@ -0,0 +1,11 @@ +'use strict'; + +function Sum(x, y, xy, x2, y2) { + this.x = x; + this.y = y; + this.xy = xy; + this.x2 = x2; + this.y2 = y2; +} + +module.exports = Sum; \ No newline at end of file diff --git a/image-vectorize/plugin/vendor/potrace/utils.js b/image-vectorize/plugin/vendor/potrace/utils.js new file mode 100644 index 0000000..bbd1fdf --- /dev/null +++ b/image-vectorize/plugin/vendor/potrace/utils.js @@ -0,0 +1,253 @@ +'use strict'; + +var Point = require('./types/Point'); +var attrRegexps = {}; + +function getAttrRegexp(attrName) { + if (attrRegexps[attrName]) { + return attrRegexps[attrName]; + } + + attrRegexps[attrName] = new RegExp(' ' + attrName + '="((?:\\\\(?=")"|[^"])+)"', 'i'); + return attrRegexps[attrName]; +} + +function setHtmlAttribute(html, attrName, value) { + var attr = ' ' + attrName + '="' + value + '"'; + + if (html.indexOf(' ' + attrName + '="') === -1) { + html = html.replace(/<[a-z]+/i, function(beginning) { return beginning + attr; }); + } else { + html = html.replace(getAttrRegexp(attrName), attr); + } + + return html; +} + +function fixed(number) { + return number.toFixed(3).replace('.000', ''); +} + +function mod(a, n) { + return a >= n ? a % n : a>=0 ? a : n-1-(-1-a) % n; +} + +function xprod(p1, p2) { + return p1.x * p2.y - p1.y * p2.x; +} + +function cyclic(a, b, c) { + if (a <= c) { + return (a <= b && b < c); + } else { + return (a <= b || b < c); + } +} + +function sign(i) { + return i > 0 ? 1 : i < 0 ? -1 : 0; +} + +function quadform(Q, w) { + var v = new Array(3), i, j, sum; + + v[0] = w.x; + v[1] = w.y; + v[2] = 1; + sum = 0.0; + + for (i=0; i<3; i++) { + for (j=0; j<3; j++) { + sum += v[i] * Q.at(i, j) * v[j]; + } + } + return sum; +} + +function interval(lambda, a, b) { + var res = new Point(); + + res.x = a.x + lambda * (b.x - a.x); + res.y = a.y + lambda * (b.y - a.y); + return res; +} + +function dorth_infty(p0, p2) { + var r = new Point(); + + r.y = sign(p2.x - p0.x); + r.x = -sign(p2.y - p0.y); + + return r; +} + +function ddenom(p0, p2) { + var r = dorth_infty(p0, p2); + + return r.y * (p2.x - p0.x) - r.x * (p2.y - p0.y); +} + +function dpara(p0, p1, p2) { + var x1, y1, x2, y2; + + x1 = p1.x - p0.x; + y1 = p1.y - p0.y; + x2 = p2.x - p0.x; + y2 = p2.y - p0.y; + + return x1 * y2 - x2 * y1; +} + +function cprod(p0, p1, p2, p3) { + var x1, y1, x2, y2; + + x1 = p1.x - p0.x; + y1 = p1.y - p0.y; + x2 = p3.x - p2.x; + y2 = p3.y - p2.y; + + return x1 * y2 - x2 * y1; +} + +function iprod(p0, p1, p2) { + var x1, y1, x2, y2; + + x1 = p1.x - p0.x; + y1 = p1.y - p0.y; + x2 = p2.x - p0.x; + y2 = p2.y - p0.y; + + return x1*x2 + y1*y2; +} + +function iprod1(p0, p1, p2, p3) { + var x1, y1, x2, y2; + + x1 = p1.x - p0.x; + y1 = p1.y - p0.y; + x2 = p3.x - p2.x; + y2 = p3.y - p2.y; + + return x1 * x2 + y1 * y2; +} + +function ddist(p, q) { + return Math.sqrt((p.x - q.x) * (p.x - q.x) + (p.y - q.y) * (p.y - q.y)); +} + +module.exports = { + luminance: function (r, g, b) { + return Math.round(0.2126 * r + 0.7153 * g + 0.0721 * b); + }, + + between: function(val, min, max) { + return val >= min && val <= max; + }, + + clamp: function(val, min, max) { + return Math.min(max, Math.max(min, val)); + }, + + isNumber: function(val) { + return typeof val === 'number'; + }, + + setHtmlAttr: setHtmlAttribute, + + /** + * Generates path instructions for given curve + * + * @param {Curve} curve + * @param {Number} [scale] + * @returns {string} + */ + renderCurve: function(curve, scale) { + scale = scale || { x: 1, y: 1 }; + + var startingPoint = curve.c[(curve.n - 1) * 3 + 2]; + + var path = [ + 'M ' + + fixed(startingPoint.x * scale.x) + ' ' + + fixed(startingPoint.y * scale.y) + ]; + + curve.tag.forEach(function(tag, i) { + var i3 = i * 3; + var p0 = curve.c[i3]; + var p1 = curve.c[i3 + 1]; + var p2 = curve.c[i3 + 2]; + + if (tag === "CURVE") { + path.push( + 'C ' + + fixed(p0.x * scale.x) + ' ' + fixed(p0.y * scale.y) + ', ' + + fixed(p1.x * scale.x) + ' ' + fixed(p1.y * scale.y) + ', ' + + fixed(p2.x * scale.x) + ' ' + fixed(p2.y * scale.y) + ); + } else if (tag === "CORNER") { + path.push( + 'L ' + + fixed(p1.x * scale.x) + ' ' + fixed(p1.y * scale.y) + ' ' + + fixed(p2.x * scale.x) + ' ' + fixed(p2.y * scale.y) + ); + } + }); + + return path.join(' '); + }, + + bezier: function bezier(t, p0, p1, p2, p3) { + var s = 1 - t, res = new Point(); + + res.x = s*s*s*p0.x + 3*(s*s*t)*p1.x + 3*(t*t*s)*p2.x + t*t*t*p3.x; + res.y = s*s*s*p0.y + 3*(s*s*t)*p1.y + 3*(t*t*s)*p2.y + t*t*t*p3.y; + + return res; + }, + + tangent: function tangent(p0, p1, p2, p3, q0, q1) { + var A, B, C, a, b, c, d, s, r1, r2; + + A = cprod(p0, p1, q0, q1); + B = cprod(p1, p2, q0, q1); + C = cprod(p2, p3, q0, q1); + + a = A - 2 * B + C; + b = -2 * A + 2 * B; + c = A; + + d = b * b - 4 * a * c; + + if (a===0 || d<0) { + return -1.0; + } + + s = Math.sqrt(d); + + r1 = (-b + s) / (2 * a); + r2 = (-b - s) / (2 * a); + + if (r1 >= 0 && r1 <= 1) { + return r1; + } else if (r2 >= 0 && r2 <= 1) { + return r2; + } else { + return -1.0; + } + }, + + mod: mod, + xprod: xprod, + cyclic: cyclic, + sign: sign, + quadform: quadform, + interval: interval, + dorth_infty: dorth_infty, + ddenom: ddenom, + dpara: dpara, + cprod: cprod, + iprod: iprod, + iprod1: iprod1, + ddist: ddist +}; \ No newline at end of file diff --git a/image-vectorize/plugin/vendor/vtracer.js b/image-vectorize/plugin/vendor/vtracer.js deleted file mode 100644 index 31cf78c..0000000 --- a/image-vectorize/plugin/vendor/vtracer.js +++ /dev/null @@ -1,452 +0,0 @@ -let wasm; - -function isLikeNone(x) { - return x === undefined || x === null; -} - -let cachedDataViewMemory0 = null; - -function getDataViewMemory0() { - if (cachedDataViewMemory0 === null || cachedDataViewMemory0.buffer.detached === true || (cachedDataViewMemory0.buffer.detached === undefined && cachedDataViewMemory0.buffer !== wasm.memory.buffer)) { - cachedDataViewMemory0 = new DataView(wasm.memory.buffer); - } - return cachedDataViewMemory0; -} - -function debugString(val) { - // primitive types - const type = typeof val; - if (type == 'number' || type == 'boolean' || val == null) { - return `${val}`; - } - if (type == 'string') { - return `"${val}"`; - } - if (type == 'symbol') { - const description = val.description; - if (description == null) { - return 'Symbol'; - } else { - return `Symbol(${description})`; - } - } - if (type == 'function') { - const name = val.name; - if (typeof name == 'string' && name.length > 0) { - return `Function(${name})`; - } else { - return 'Function'; - } - } - // objects - if (Array.isArray(val)) { - const length = val.length; - let debug = '['; - if (length > 0) { - debug += debugString(val[0]); - } - for(let i = 1; i < length; i++) { - debug += ', ' + debugString(val[i]); - } - debug += ']'; - return debug; - } - // Test for built-in - const builtInMatches = /\[object ([^\]]+)\]/.exec(toString.call(val)); - let className; - if (builtInMatches && builtInMatches.length > 1) { - className = builtInMatches[1]; - } else { - // Failed to match the standard '[object ClassName]' - return toString.call(val); - } - if (className == 'Object') { - // we're a user defined class or Object - // JSON.stringify avoids problems with cycles, and is generally much - // easier than looping through ownProperties of `val`. - try { - return 'Object(' + JSON.stringify(val) + ')'; - } catch (_) { - return 'Object'; - } - } - // errors - if (val instanceof Error) { - return `${val.name}: ${val.message}\n${val.stack}`; - } - // TODO we could test for more things here, like `Set`s and `Map`s. - return className; -} - -let WASM_VECTOR_LEN = 0; - -let cachedUint8ArrayMemory0 = null; - -function getUint8ArrayMemory0() { - if (cachedUint8ArrayMemory0 === null || cachedUint8ArrayMemory0.byteLength === 0) { - cachedUint8ArrayMemory0 = new Uint8Array(wasm.memory.buffer); - } - return cachedUint8ArrayMemory0; -} - -const cachedTextEncoder = (typeof TextEncoder !== 'undefined' ? new TextEncoder('utf-8') : { encode: () => { throw Error('TextEncoder not available') } } ); - -const encodeString = (typeof cachedTextEncoder.encodeInto === 'function' - ? function (arg, view) { - return cachedTextEncoder.encodeInto(arg, view); -} - : function (arg, view) { - const buf = cachedTextEncoder.encode(arg); - view.set(buf); - return { - read: arg.length, - written: buf.length - }; -}); - -function passStringToWasm0(arg, malloc, realloc) { - - if (realloc === undefined) { - const buf = cachedTextEncoder.encode(arg); - const ptr = malloc(buf.length, 1) >>> 0; - getUint8ArrayMemory0().subarray(ptr, ptr + buf.length).set(buf); - WASM_VECTOR_LEN = buf.length; - return ptr; - } - - let len = arg.length; - let ptr = malloc(len, 1) >>> 0; - - const mem = getUint8ArrayMemory0(); - - let offset = 0; - - for (; offset < len; offset++) { - const code = arg.charCodeAt(offset); - if (code > 0x7F) break; - mem[ptr + offset] = code; - } - - if (offset !== len) { - if (offset !== 0) { - arg = arg.slice(offset); - } - ptr = realloc(ptr, len, len = offset + arg.length * 3, 1) >>> 0; - const view = getUint8ArrayMemory0().subarray(ptr + offset, ptr + len); - const ret = encodeString(arg, view); - - offset += ret.written; - ptr = realloc(ptr, len, offset, 1) >>> 0; - } - - WASM_VECTOR_LEN = offset; - return ptr; -} - -const cachedTextDecoder = (typeof TextDecoder !== 'undefined' ? new TextDecoder('utf-8', { ignoreBOM: true, fatal: true }) : { decode: () => { throw Error('TextDecoder not available') } } ); - -if (typeof TextDecoder !== 'undefined') { cachedTextDecoder.decode(); }; - -function getStringFromWasm0(ptr, len) { - ptr = ptr >>> 0; - return cachedTextDecoder.decode(getUint8ArrayMemory0().subarray(ptr, ptr + len)); -} - -function passArray8ToWasm0(arg, malloc) { - const ptr = malloc(arg.length * 1, 1) >>> 0; - getUint8ArrayMemory0().set(arg, ptr / 1); - WASM_VECTOR_LEN = arg.length; - return ptr; -} -/** - * @param {Uint8Array} pixels - * @param {number} width - * @param {number} height - * @param {any} config_js - * @returns {string} - */ -export function to_svg(pixels, width, height, config_js) { - let deferred2_0; - let deferred2_1; - try { - const ptr0 = passArray8ToWasm0(pixels, wasm.__wbindgen_malloc); - const len0 = WASM_VECTOR_LEN; - const ret = wasm.to_svg(ptr0, len0, width, height, config_js); - deferred2_0 = ret[0]; - deferred2_1 = ret[1]; - return getStringFromWasm0(ret[0], ret[1]); - } finally { - wasm.__wbindgen_free(deferred2_0, deferred2_1, 1); - } -} - -async function __wbg_load(module, imports) { - if (typeof Response === 'function' && module instanceof Response) { - if (typeof WebAssembly.instantiateStreaming === 'function') { - try { - return await WebAssembly.instantiateStreaming(module, imports); - - } catch (e) { - if (module.headers.get('Content-Type') != 'application/wasm') { - console.warn("`WebAssembly.instantiateStreaming` failed because your server does not serve Wasm with `application/wasm` MIME type. Falling back to `WebAssembly.instantiate` which is slower. Original error:\n", e); - - } else { - throw e; - } - } - } - - const bytes = await module.arrayBuffer(); - return await WebAssembly.instantiate(bytes, imports); - - } else { - const instance = await WebAssembly.instantiate(module, imports); - - if (instance instanceof WebAssembly.Instance) { - return { instance, module }; - - } else { - return instance; - } - } -} - -function __wbg_get_imports() { - const imports = {}; - imports.wbg = {}; - imports.wbg.__wbg_buffer_609cc3eee51ed158 = function(arg0) { - const ret = arg0.buffer; - return ret; - }; - imports.wbg.__wbg_entries_3265d4158b33e5dc = function(arg0) { - const ret = Object.entries(arg0); - return ret; - }; - imports.wbg.__wbg_error_524f506f44df1645 = function(arg0) { - console.error(arg0); - }; - imports.wbg.__wbg_get_b9b93047fe3cf45b = function(arg0, arg1) { - const ret = arg0[arg1 >>> 0]; - return ret; - }; - imports.wbg.__wbg_getwithrefkey_1dc361bd10053bfe = function(arg0, arg1) { - const ret = arg0[arg1]; - return ret; - }; - imports.wbg.__wbg_instanceof_ArrayBuffer_e14585432e3737fc = function(arg0) { - let result; - try { - result = arg0 instanceof ArrayBuffer; - } catch (_) { - result = false; - } - const ret = result; - return ret; - }; - imports.wbg.__wbg_instanceof_Uint8Array_17156bcf118086a9 = function(arg0) { - let result; - try { - result = arg0 instanceof Uint8Array; - } catch (_) { - result = false; - } - const ret = result; - return ret; - }; - imports.wbg.__wbg_isSafeInteger_343e2beeeece1bb0 = function(arg0) { - const ret = Number.isSafeInteger(arg0); - return ret; - }; - imports.wbg.__wbg_length_a446193dc22c12f8 = function(arg0) { - const ret = arg0.length; - return ret; - }; - imports.wbg.__wbg_length_e2d2a49132c1b256 = function(arg0) { - const ret = arg0.length; - return ret; - }; - imports.wbg.__wbg_new_a12002a7f91c75be = function(arg0) { - const ret = new Uint8Array(arg0); - return ret; - }; - imports.wbg.__wbg_set_65595bdd868b3009 = function(arg0, arg1, arg2) { - arg0.set(arg1, arg2 >>> 0); - }; - imports.wbg.__wbindgen_as_number = function(arg0) { - const ret = +arg0; - return ret; - }; - imports.wbg.__wbindgen_bigint_from_u64 = function(arg0) { - const ret = BigInt.asUintN(64, arg0); - return ret; - }; - imports.wbg.__wbindgen_bigint_get_as_i64 = function(arg0, arg1) { - const v = arg1; - const ret = typeof(v) === 'bigint' ? v : undefined; - getDataViewMemory0().setBigInt64(arg0 + 8 * 1, isLikeNone(ret) ? BigInt(0) : ret, true); - getDataViewMemory0().setInt32(arg0 + 4 * 0, !isLikeNone(ret), true); - }; - imports.wbg.__wbindgen_boolean_get = function(arg0) { - const v = arg0; - const ret = typeof(v) === 'boolean' ? (v ? 1 : 0) : 2; - return ret; - }; - imports.wbg.__wbindgen_debug_string = function(arg0, arg1) { - const ret = debugString(arg1); - const ptr1 = passStringToWasm0(ret, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc); - const len1 = WASM_VECTOR_LEN; - getDataViewMemory0().setInt32(arg0 + 4 * 1, len1, true); - getDataViewMemory0().setInt32(arg0 + 4 * 0, ptr1, true); - }; - imports.wbg.__wbindgen_error_new = function(arg0, arg1) { - const ret = new Error(getStringFromWasm0(arg0, arg1)); - return ret; - }; - imports.wbg.__wbindgen_in = function(arg0, arg1) { - const ret = arg0 in arg1; - return ret; - }; - imports.wbg.__wbindgen_init_externref_table = function() { - const table = wasm.__wbindgen_export_2; - const offset = table.grow(4); - table.set(0, undefined); - table.set(offset + 0, undefined); - table.set(offset + 1, null); - table.set(offset + 2, true); - table.set(offset + 3, false); - ; - }; - imports.wbg.__wbindgen_is_bigint = function(arg0) { - const ret = typeof(arg0) === 'bigint'; - return ret; - }; - imports.wbg.__wbindgen_is_object = function(arg0) { - const val = arg0; - const ret = typeof(val) === 'object' && val !== null; - return ret; - }; - imports.wbg.__wbindgen_is_string = function(arg0) { - const ret = typeof(arg0) === 'string'; - return ret; - }; - imports.wbg.__wbindgen_is_undefined = function(arg0) { - const ret = arg0 === undefined; - return ret; - }; - imports.wbg.__wbindgen_jsval_eq = function(arg0, arg1) { - const ret = arg0 === arg1; - return ret; - }; - imports.wbg.__wbindgen_jsval_loose_eq = function(arg0, arg1) { - const ret = arg0 == arg1; - return ret; - }; - imports.wbg.__wbindgen_memory = function() { - const ret = wasm.memory; - return ret; - }; - imports.wbg.__wbindgen_number_get = function(arg0, arg1) { - const obj = arg1; - const ret = typeof(obj) === 'number' ? obj : undefined; - getDataViewMemory0().setFloat64(arg0 + 8 * 1, isLikeNone(ret) ? 0 : ret, true); - getDataViewMemory0().setInt32(arg0 + 4 * 0, !isLikeNone(ret), true); - }; - imports.wbg.__wbindgen_string_get = function(arg0, arg1) { - const obj = arg1; - const ret = typeof(obj) === 'string' ? obj : undefined; - var ptr1 = isLikeNone(ret) ? 0 : passStringToWasm0(ret, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc); - var len1 = WASM_VECTOR_LEN; - getDataViewMemory0().setInt32(arg0 + 4 * 1, len1, true); - getDataViewMemory0().setInt32(arg0 + 4 * 0, ptr1, true); - }; - imports.wbg.__wbindgen_string_new = function(arg0, arg1) { - const ret = getStringFromWasm0(arg0, arg1); - return ret; - }; - imports.wbg.__wbindgen_throw = function(arg0, arg1) { - throw new Error(getStringFromWasm0(arg0, arg1)); - }; - - return imports; -} - -function __wbg_init_memory(imports, memory) { - -} - -function __wbg_finalize_init(instance, module) { - wasm = instance.exports; - __wbg_init.__wbindgen_wasm_module = module; - cachedDataViewMemory0 = null; - cachedUint8ArrayMemory0 = null; - - - wasm.__wbindgen_start(); - return wasm; -} - -function initSync(module) { - if (wasm !== undefined) return wasm; - - - if (typeof module !== 'undefined') { - if (Object.getPrototypeOf(module) === Object.prototype) { - ({module} = module) - } else { - console.warn('using deprecated parameters for `initSync()`; pass a single object instead') - } - } - - const imports = __wbg_get_imports(); - - __wbg_init_memory(imports); - - if (!(module instanceof WebAssembly.Module)) { - module = new WebAssembly.Module(module); - } - - const instance = new WebAssembly.Instance(module, imports); - - return __wbg_finalize_init(instance, module); -} - -async function __wbg_init(module_or_path) { - if (wasm !== undefined) return wasm; - - - if (typeof module_or_path !== 'undefined') { - if (Object.getPrototypeOf(module_or_path) === Object.prototype) { - ({module_or_path} = module_or_path) - } else { - console.warn('using deprecated parameters for the initialization function; pass a single object instead') - } - } - - if (typeof module_or_path === 'undefined') { - // 本地改动:上游这里用 new URL('vtracer_bg.wasm', import.meta.url) 默认取同目录 wasm。 - // 本插件把 wasm 以 base64 内联(宿主发布链路只接受单个 .js),且产物是 IIFE(无 import.meta), - // 永远由调用方显式传字节,因此这里直接报错而不是留一条会崩的默认路径。 - throw new Error('vtracer: 必须显式传入 wasm 字节(本插件内联分发,不支持默认路径加载)') - } - const imports = __wbg_get_imports(); - - if (typeof module_or_path === 'string' || (typeof Request === 'function' && module_or_path instanceof Request) || (typeof URL === 'function' && module_or_path instanceof URL)) { - module_or_path = fetch(module_or_path); - } - - __wbg_init_memory(imports); - - const { instance, module } = await __wbg_load(await module_or_path, imports); - - return __wbg_finalize_init(instance, module); -} - -export { initSync }; -export default __wbg_init; - -// 本地改动:visioncortex 在部分极端参数下会 abort(wasm 报 unreachable), -// 此时实例已损坏、后续调用全部失败;而 __wbg_init 见到 wasm 已存在会直接返回旧实例。 -// 因此提供一个显式复位钩子,让上层的「出错了就重建实例重试一次」成为可能。 -export function __reset_wasm() { - wasm = undefined; -} diff --git a/image-vectorize/plugin/vendor/vtracer.wasm b/image-vectorize/plugin/vendor/vtracer.wasm deleted file mode 100644 index 2aa1eea7c1f168e07ce4cadfe60432a1d998363e..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 136862 zcmeFa4VWF*S?5_F_pAHf+g&ZSq?TH?&n+u)E0z*T)@LR|y0o@rp%`aKU;~>O$+B9u zyA{hVD~bccY9~rif&c-YnIvmSOZE`MI7GYSnRplnlwAW}a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rzs~Q*m5^zyy53ZWngZxXV-&(Fp`#;n8*S!t~tr7XrsQ9R$YTeU3=VJfx zZ#&iB;8xere_!jt$!Sc_6u%#fta&cSiH1P#W~6-v=rW6{Bnsh$0(5Gbb_4k$@W6U~ zB5qo^b3y;_?=f*}pm`1#ox;ZACI%6#*@v$>+arq2^y=c52LxYFof|s2MWh4 z+!716mwQ`qc0DYZ{n&QZf+O6#^cUzLTmrmMZXEH>sc91p^p1?$p)N;Bk;9o2d#i?= z)wS9yV@H2sj? { - // image-vectorize/plugin/ui.css - var ui_default = `/* 位图转矢量:全屏模态。深色,与「标注 / 修图」同一套视觉语言。 - CSP:由宿主 style-src 'unsafe-inline' 放行,运行时注入
') -// 测试图:白底 + 红圆 + 蓝圆角矩形 + 黑色中文 + 绿色曲线(实心/圆角/文字/描边四类形态) +// 测试图:白底 + 红圆 + 蓝圆角矩形 + 黑色中文 + 绿色曲线(实心/圆角/文字/描边四类形态), +// 外加几个 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() diff --git a/image-vectorize/tools/trace-cli.mjs b/image-vectorize/tools/trace-cli.mjs new file mode 100644 index 0000000..9b84167 --- /dev/null +++ b/image-vectorize/tools/trace-cli.mjs @@ -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 目录] +// +// 产物:/-.svg + 一张对比图 /-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('') +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()