Files
image-workbench-desktop/plugins/runtime/plugin-image-vectorize.0e5a7fa018b2.js
T
qiqi c81a107b5f feat(tokens): M4-B6 收尾 —— 半像素清零 + 插件契约文件级豁免归零(3.26.49)
- style.css 剩余 16 处半像素字号并入闭集,删 2 条归并后重复的规则;守卫收紧为全文件断言
- 裁定 --iwb-control-h 不扩到全局控件(并排表单 vs 成组紧凑控件),新增「全局 input 不得写死 height」守卫
- plugin-theme-contract-test 重写:ALLOW_FILES 6 → 0,改为私有皮肤自声明(skin) + chroma 强调色判据 + 行内内容色标记;私有皮肤必须自洽(不引用宿主颜色 token)
- token-audit 插件段同口径分三类报数;插件侧中性色写死归零
- 插件仓同步 4 个版本:browser 1.7.1 / batch-export 1.2.1 / image-annotate 1.20.7 / image-vectorize 0.6.1
- 视觉基线 8 张更新(含画布场景的字号栅格化变化),A/B 回退确认非环境噪声,复核 12/12
2026-11-23 17:09:46 +08:00

3798 lines
142 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
// 手写 manifest —— 必须保持单引号:scripts/validate.mjs 只认单引号形式,而 esbuild 打印器会改成双引号,
// 所以本文件不经 esbuild 转换,由 build-plugin.mjs 原样放在产物最前面(banner)。
//
// 为什么必须排在最前:校验器用「文件里第一个形如 id 冒号 单引号 的字面量」判定插件 id,
// 排在 bundle 之前才能保证取到的是下面这份 manifest。
// ⚠️ 因此本文件的注释里不要写出那种字面量形态(会抢先匹配),要描述就直接说「id 字面量」。
//
// 版本占位符由构建脚本用 package.json 的 version 替换,保证两处永不漂移。
// skin: 'private' = 自绘深色工具 UI(#1b1b22 系列),不跟随宿主主题。
// 代价由宿主契约测试钉死:声明 private 的插件不得引用宿主颜色 var(--iwb-*),只能自洽。
var __IWB_VECTORIZE_MANIFEST__ = {
id: 'image-vectorize',
name: '位图转矢量',
version: '0.6.1',
apiVersion: 1,
skin: 'private',
capabilities: ['commands', 'nodeActions', 'canvas', 'canvasWrite'],
settings: {
preset: { type: 'string', default: 'text' },
mode: { type: 'string', default: 'gray' },
levels: { type: 'number', default: 3 },
threshold: { type: 'number', default: -1 },
turdSize: { type: 'number', default: 3 },
alphaMax: { type: 'number', default: 1 },
optTolerance: { type: 'number', default: 0.05 },
invert: { type: 'boolean', default: false },
color: { type: 'string', default: '#1a1a1a' },
bg: { type: 'string', default: '#ffffff' },
bgExport: { type: 'boolean', default: false },
outScale: { type: 'number', default: 2 },
advOpen: { type: 'boolean', default: true },
splitIslands: { type: 'boolean', default: true }
},
}
"use strict";
(() => {
var __create = Object.create;
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getProtoOf = Object.getPrototypeOf;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x, {
get: (a, b) => (typeof require !== "undefined" ? require : a)[b]
}) : x)(function(x) {
if (typeof require !== "undefined") return require.apply(this, arguments);
throw Error('Dynamic require of "' + x + '" is not supported');
});
var __commonJS = (cb, mod) => function __require2() {
return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
// If the importer is in node compatibility mode or this is not an ESM
// file that has been converted to a CommonJS file using a Babel-
// compatible transform (i.e. "__esModule" has not been set), then set
// "default" to the CommonJS "module.exports" for node compatibility.
isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
mod
));
// image-vectorize/plugin/vendor/potrace/types/Point.js
var require_Point = __commonJS({
"image-vectorize/plugin/vendor/potrace/types/Point.js"(exports, module) {
"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;
}
});
// image-vectorize/plugin/vendor/potrace/utils.js
var require_utils = __commonJS({
"image-vectorize/plugin/vendor/potrace/utils.js"(exports, module) {
"use strict";
var Point = require_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;
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;
}
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;
}
},
mod,
xprod,
cyclic,
sign,
quadform,
interval,
dorth_infty,
ddenom,
dpara,
cprod,
iprod,
iprod1,
ddist
};
}
});
// image-vectorize/plugin/vendor/potrace/types/Histogram.js
var require_Histogram = __commonJS({
"image-vectorize/plugin/vendor/potrace/types/Histogram.js"(exports, module) {
"use strict";
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;
function index(x, y) {
return COLOR_DEPTH * x + y;
}
function normalizeMinMax(levelMin, levelMax) {
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];
}
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;
for (i = 1; i < COLOR_DEPTH; ++i) {
idx = index(i, i);
tmp = this.data[i] / pixelsTotal;
P[idx] = tmp;
S[idx] = i * tmp;
}
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;
}
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)];
}
}
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;
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) {
iterateRecursive(i, variance, indexes, depth);
} else {
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;
var mostPixelsPerLevel = 0;
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);
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;
}
});
// image-vectorize/plugin/vendor/potrace/types/Bitmap.js
var require_Bitmap = __commonJS({
"image-vectorize/plugin/vendor/potrace/types/Bitmap.js"(exports, module) {
"use strict";
var Point = require_Point();
var utils = require_utils();
var Histogram;
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 Histogram2 = require_Histogram();
if (this._histogram) {
return this._histogram;
}
this._histogram = new Histogram2(this);
return this._histogram;
}
};
}
});
// image-vectorize/plugin/vendor/potrace/types/Curve.js
var require_Curve = __commonJS({
"image-vectorize/plugin/vendor/potrace/types/Curve.js"(exports, module) {
"use strict";
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;
}
});
// image-vectorize/plugin/vendor/potrace/types/Path.js
var require_Path = __commonJS({
"image-vectorize/plugin/vendor/potrace/types/Path.js"(exports, module) {
"use strict";
function Path() {
this.area = 0;
this.len = 0;
this.curve = {};
this.pt = [];
this.minX = 1e5;
this.minY = 1e5;
this.maxX = -1;
this.maxY = -1;
}
module.exports = Path;
}
});
// image-vectorize/plugin/vendor/potrace/types/Quad.js
var require_Quad = __commonJS({
"image-vectorize/plugin/vendor/potrace/types/Quad.js"(exports, module) {
"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;
}
});
// image-vectorize/plugin/vendor/potrace/types/Sum.js
var require_Sum = __commonJS({
"image-vectorize/plugin/vendor/potrace/types/Sum.js"(exports, module) {
"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;
}
});
// image-vectorize/plugin/vendor/potrace/types/Opti.js
var require_Opti = __commonJS({
"image-vectorize/plugin/vendor/potrace/types/Opti.js"(exports, module) {
"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;
}
});
// image-vectorize/plugin/vendor/potrace/Potrace.js
var require_Potrace = __commonJS({
"image-vectorize/plugin/vendor/potrace/Potrace.js"(exports, module) {
"use strict";
var Bitmap = require_Bitmap();
var Curve = require_Curve();
var Point = require_Point();
var Path = require_Path();
var Quad = require_Quad();
var Sum = require_Sum();
var Opti = require_Opti();
var utils = require_utils();
function Potrace2(options) {
this._luminanceData = null;
this._pathlist = [];
this._imageLoadingIdentifier = null;
this._imageLoaded = false;
this._processed = false;
this._params = {
turnPolicy: Potrace2.TURNPOLICY_MINORITY,
turdSize: 2,
alphaMax: 1,
optCurve: true,
optTolerance: 0.2,
threshold: Potrace2.THRESHOLD_AUTO,
blackOnWhite: true,
color: Potrace2.COLOR_AUTO,
background: Potrace2.COLOR_TRANSPARENT,
width: null,
height: null
};
if (options) {
this.setParameters(options);
}
}
Potrace2.COLOR_AUTO = "auto";
Potrace2.COLOR_TRANSPARENT = "transparent";
Potrace2.THRESHOLD_AUTO = -1;
Potrace2.TURNPOLICY_BLACK = "black";
Potrace2.TURNPOLICY_WHITE = "white";
Potrace2.TURNPOLICY_LEFT = "left";
Potrace2.TURNPOLICY_RIGHT = "right";
Potrace2.TURNPOLICY_MINORITY = "minority";
Potrace2.TURNPOLICY_MAJORITY = "majority";
var SUPPORTED_TURNPOLICY_VALUES = [
Potrace2.TURNPOLICY_BLACK,
Potrace2.TURNPOLICY_WHITE,
Potrace2.TURNPOLICY_LEFT,
Potrace2.TURNPOLICY_RIGHT,
Potrace2.TURNPOLICY_MINORITY,
Potrace2.TURNPOLICY_MAJORITY
];
Potrace2.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 === Potrace2.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;
});
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 path2 = new Path(), x = point.x, y = point.y, dirx = 0, diry = 1, tmp;
path2.sign = blackMap.getValueAt(point.x, point.y) ? "+" : "-";
while (1) {
path2.pt.push(new Point(x, y));
if (x > path2.maxX)
path2.maxX = x;
if (x < path2.minX)
path2.minX = x;
if (y > path2.maxY)
path2.maxY = y;
if (y < path2.minY)
path2.minY = y;
path2.len++;
x += dirx;
y += diry;
path2.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" && path2.sign === "+" || self._params.turnPolicy === "white" && path2.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 path2;
}
function xorPath(path2) {
var y1 = path2.pt[0].y, len = path2.len, x, y, maxX, minY, i, j, indx;
for (i = 1; i < len; i++) {
x = path2.pt[i].x;
y = path2.pt[i].y;
if (y !== y1) {
minY = y1 < y ? y1 : y;
maxX = path2.maxX;
for (j = x; j < maxX; j++) {
indx = blackMap.pointToIndex(j, minY);
blackMap.data[indx] = blackMap.data[indx] ? 0 : 1;
}
y1 = y;
}
}
}
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(path2) {
var i2, x, y;
path2.x0 = path2.pt[0].x;
path2.y0 = path2.pt[0].y;
path2.sums = [];
var s = path2.sums;
s.push(new Sum(0, 0, 0, 0, 0));
for (i2 = 0; i2 < path2.len; i2++) {
x = path2.pt[i2].x - path2.x0;
y = path2.pt[i2].y - path2.y0;
s.push(new Sum(
s[i2].x + x,
s[i2].y + y,
s[i2].xy + x * y,
s[i2].x2 + x * x,
s[i2].y2 + y * y
));
}
}
function calcLon(path2) {
var n = path2.len, pt = path2.pt, dir, pivk = new Array(n), nc = new Array(n), ct = new Array(4);
path2.lon = new Array(n);
var constraint = [new Point(), new Point()], cur = new Point(), off = new Point(), dk = new Point(), foundk;
var i2, j, k1, a, b, c, d, k = 0;
for (i2 = n - 1; i2 >= 0; i2--) {
if (pt[i2].x != pt[k].x && pt[i2].y != pt[k].y) {
k = i2 + 1;
}
nc[i2] = k;
}
for (i2 = n - 1; i2 >= 0; i2--) {
ct[0] = ct[1] = ct[2] = ct[3] = 0;
dir = (3 + 3 * (pt[utils.mod(i2 + 1, n)].x - pt[i2].x) + (pt[utils.mod(i2 + 1, n)].y - pt[i2].y)) / 2;
ct[dir]++;
constraint[0].x = 0;
constraint[0].y = 0;
constraint[1].x = 0;
constraint[1].y = 0;
k = nc[i2];
k1 = i2;
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[i2] = k1;
foundk = 1;
break;
}
cur.x = pt[k].x - pt[i2].x;
cur.y = pt[k].y - pt[i2].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, i2, 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[i2].x;
cur.y = pt[k1].y - pt[i2].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 = 1e7;
if (b < 0) {
j = Math.floor(a / -b);
}
if (d > 0) {
j = Math.min(j, Math.floor(-c / d));
}
pivk[i2] = utils.mod(k1 + j, n);
}
}
j = pivk[n - 1];
path2.lon[n - 1] = j;
for (i2 = n - 2; i2 >= 0; i2--) {
if (utils.cyclic(i2 + 1, pivk[i2], j)) {
j = pivk[i2];
}
path2.lon[i2] = j;
}
for (i2 = n - 1; utils.cyclic(utils.mod(i2 + 1, n), j, path2.lon[i2]); i2--) {
path2.lon[i2] = j;
}
}
function bestPolygon(path2) {
function penalty3(path3, i3, j2) {
var n2 = path3.len, pt = path3.pt, sums = path3.sums;
var x, y, xy, x2, y2, k2, a, b, c2, s, px, py, ex, ey, r = 0;
if (j2 >= n2) {
j2 -= n2;
r = 1;
}
if (r === 0) {
x = sums[j2 + 1].x - sums[i3].x;
y = sums[j2 + 1].y - sums[i3].y;
x2 = sums[j2 + 1].x2 - sums[i3].x2;
xy = sums[j2 + 1].xy - sums[i3].xy;
y2 = sums[j2 + 1].y2 - sums[i3].y2;
k2 = j2 + 1 - i3;
} else {
x = sums[j2 + 1].x - sums[i3].x + sums[n2].x;
y = sums[j2 + 1].y - sums[i3].y + sums[n2].y;
x2 = sums[j2 + 1].x2 - sums[i3].x2 + sums[n2].x2;
xy = sums[j2 + 1].xy - sums[i3].xy + sums[n2].xy;
y2 = sums[j2 + 1].y2 - sums[i3].y2 + sums[n2].y2;
k2 = j2 + 1 - i3 + n2;
}
px = (pt[i3].x + pt[j2].x) / 2 - pt[0].x;
py = (pt[i3].y + pt[j2].y) / 2 - pt[0].y;
ey = pt[j2].x - pt[i3].x;
ex = -(pt[j2].y - pt[i3].y);
a = (x2 - 2 * x * px) / k2 + px * px;
b = (xy - x * py - y * px) / k2 + px * py;
c2 = (y2 - 2 * y * py) / k2 + py * py;
s = ex * ex * a + 2 * ex * ey * b + ey * ey * c2;
return Math.sqrt(s);
}
var i2, j, m, k, n = path2.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 (i2 = 0; i2 < n; i2++) {
c = utils.mod(path2.lon[utils.mod(i2 - 1, n)] - 1, n);
if (c == i2) {
c = utils.mod(i2 + 1, n);
}
if (c < i2) {
clip0[i2] = n;
} else {
clip0[i2] = c;
}
}
j = 1;
for (i2 = 0; i2 < n; i2++) {
while (j <= clip0[i2]) {
clip1[j] = i2;
j++;
}
}
i2 = 0;
for (j = 0; i2 < n; j++) {
seg0[j] = i2;
i2 = clip0[i2];
}
seg0[j] = n;
m = j;
i2 = n;
for (j = m; j > 0; j--) {
seg1[j] = i2;
i2 = clip1[i2];
}
seg1[0] = 0;
pen[0] = 0;
for (j = 1; j <= m; j++) {
for (i2 = seg1[j]; i2 <= seg0[j]; i2++) {
best = -1;
for (k = seg0[j - 1]; k >= clip1[i2]; k--) {
thispen = penalty3(path2, k, i2) + pen[k];
if (best < 0 || thispen < best) {
prev[i2] = k;
best = thispen;
}
}
pen[i2] = best;
}
}
path2.m = m;
path2.po = new Array(m);
for (i2 = n, j = m - 1; i2 > 0; j--) {
i2 = prev[i2];
path2.po[j] = i2;
}
}
function adjustVertices(path2) {
function pointslope(path3, i3, j2, ctr2, dir2) {
var n2 = path3.len, sums = path3.sums, x, y, x2, xy, y2, k2, a, b, c, lambda2, l2, r = 0;
while (j2 >= n2) {
j2 -= n2;
r += 1;
}
while (i3 >= n2) {
i3 -= n2;
r -= 1;
}
while (j2 < 0) {
j2 += n2;
r -= 1;
}
while (i3 < 0) {
i3 += n2;
r += 1;
}
x = sums[j2 + 1].x - sums[i3].x + r * sums[n2].x;
y = sums[j2 + 1].y - sums[i3].y + r * sums[n2].y;
x2 = sums[j2 + 1].x2 - sums[i3].x2 + r * sums[n2].x2;
xy = sums[j2 + 1].xy - sums[i3].xy + r * sums[n2].xy;
y2 = sums[j2 + 1].y2 - sums[i3].y2 + r * sums[n2].y2;
k2 = j2 + 1 - i3 + r * n2;
ctr2.x = x / k2;
ctr2.y = y / k2;
a = (x2 - x * x / k2) / k2;
b = (xy - x * y / k2) / k2;
c = (y2 - y * y / k2) / k2;
lambda2 = (a + c + Math.sqrt((a - c) * (a - c) + 4 * b * b)) / 2;
a -= lambda2;
c -= lambda2;
if (Math.abs(a) >= Math.abs(c)) {
l2 = Math.sqrt(a * a + b * b);
if (l2 !== 0) {
dir2.x = -b / l2;
dir2.y = a / l2;
}
} else {
l2 = Math.sqrt(c * c + b * b);
if (l2 !== 0) {
dir2.x = -c / l2;
dir2.y = b / l2;
}
}
if (l2 === 0) {
dir2.x = dir2.y = 0;
}
}
var m = path2.m, po = path2.po, n = path2.len, pt = path2.pt, x0 = path2.x0, y0 = path2.y0, ctr = new Array(m), dir = new Array(m), q = new Array(m), v = new Array(3), d, i2, j, k, l, s = new Point();
path2.curve = new Curve(m);
for (i2 = 0; i2 < m; i2++) {
j = po[utils.mod(i2 + 1, m)];
j = utils.mod(j - po[i2], n) + po[i2];
ctr[i2] = new Point();
dir[i2] = new Point();
pointslope(path2, po[i2], j, ctr[i2], dir[i2]);
}
for (i2 = 0; i2 < m; i2++) {
q[i2] = new Quad();
d = dir[i2].x * dir[i2].x + dir[i2].y * dir[i2].y;
if (d === 0) {
for (j = 0; j < 3; j++) {
for (k = 0; k < 3; k++) {
q[i2].data[j * 3 + k] = 0;
}
}
} else {
v[0] = dir[i2].y;
v[1] = -dir[i2].x;
v[2] = -v[1] * ctr[i2].y - v[0] * ctr[i2].x;
for (l = 0; l < 3; l++) {
for (k = 0; k < 3; k++) {
q[i2].data[l * 3 + k] = v[l] * v[k] / d;
}
}
}
}
var Q, w, dx, dy, det, min, cand, xmin, ymin, z;
for (i2 = 0; i2 < m; i2++) {
Q = new Quad();
w = new Point();
s.x = pt[po[i2]].x - x0;
s.y = pt[po[i2]].y - y0;
j = utils.mod(i2 - 1, m);
for (l = 0; l < 3; l++) {
for (k = 0; k < 3; k++) {
Q.data[l * 3 + k] = q[j].at(l, k) + q[i2].at(l, k);
}
}
while (1) {
det = Q.at(0, 0) * Q.at(1, 1) - Q.at(0, 1) * Q.at(1, 0);
if (det !== 0) {
w.x = (-Q.at(0, 2) * Q.at(1, 1) + Q.at(1, 2) * Q.at(0, 1)) / det;
w.y = (Q.at(0, 2) * Q.at(1, 0) - Q.at(1, 2) * Q.at(0, 0)) / det;
break;
}
if (Q.at(0, 0) > Q.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) {
path2.curve.vertex[i2] = 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) {
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) {
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;
}
}
}
path2.curve.vertex[i2] = new Point(xmin + x0, ymin + y0);
}
}
function reverse(path2) {
var curve = path2.curve, m = curve.n, v = curve.vertex, i2, j, tmp;
for (i2 = 0, j = m - 1; i2 < j; i2++, j--) {
tmp = v[i2];
v[i2] = v[j];
v[j] = tmp;
}
}
function smooth(path2) {
var m = path2.curve.n, curve = path2.curve;
var i2, j, k, dd, denom, alpha, p2, p3, p4;
for (i2 = 0; i2 < m; i2++) {
j = utils.mod(i2 + 1, m);
k = utils.mod(i2 + 2, m);
p4 = utils.interval(1 / 2, curve.vertex[k], curve.vertex[j]);
denom = utils.ddenom(curve.vertex[i2], curve.vertex[k]);
if (denom !== 0) {
dd = utils.dpara(curve.vertex[i2], curve.vertex[j], curve.vertex[k]) / denom;
dd = Math.abs(dd);
alpha = dd > 1 ? 1 - 1 / dd : 0;
alpha = alpha / 0.75;
} else {
alpha = 4 / 3;
}
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[i2], 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(path2) {
function opti_penalty(path3, i3, j2, res, opttolerance, convc2, areac2) {
var m2 = path3.curve.n, curve2 = path3.curve, vertex = curve2.vertex, k, k1, k2, conv, i12, area2, alpha2, d, d1, d2, p02, p1, p2, p3, pt2, A, R, A1, A2, A3, A4, s2, t2;
if (i3 == j2) {
return 1;
}
k = i3;
i12 = utils.mod(i3 + 1, m2);
k1 = utils.mod(k + 1, m2);
conv = convc2[k1];
if (conv === 0) {
return 1;
}
d = utils.ddist(vertex[i3], vertex[i12]);
for (k = k1; k != j2; k = k1) {
k1 = utils.mod(k + 1, m2);
k2 = utils.mod(k + 2, m2);
if (convc2[k1] != conv) {
return 1;
}
if (utils.sign(utils.cprod(vertex[i3], vertex[i12], vertex[k1], vertex[k2])) != conv) {
return 1;
}
if (utils.iprod1(vertex[i3], vertex[i12], vertex[k1], vertex[k2]) < d * utils.ddist(vertex[k1], vertex[k2]) * -0.999847695156) {
return 1;
}
}
p02 = curve2.c[utils.mod(i3, m2) * 3 + 2].copy();
p1 = vertex[utils.mod(i3 + 1, m2)].copy();
p2 = vertex[utils.mod(j2, m2)].copy();
p3 = curve2.c[utils.mod(j2, m2) * 3 + 2].copy();
area2 = areac2[j2] - areac2[i3];
area2 -= utils.dpara(vertex[0], curve2.c[i3 * 3 + 2], curve2.c[j2 * 3 + 2]) / 2;
if (i3 >= j2) {
area2 += areac2[m2];
}
A1 = utils.dpara(p02, p1, p2);
A2 = utils.dpara(p02, p1, p3);
A3 = utils.dpara(p02, p2, p3);
A4 = A1 + A3 - A2;
if (A2 == A1) {
return 1;
}
t2 = A3 / (A3 - A4);
s2 = A2 / (A2 - A1);
A = A2 * t2 / 2;
if (A === 0) {
return 1;
}
R = area2 / A;
alpha2 = 2 - Math.sqrt(4 - R / 0.3);
res.c[0] = utils.interval(t2 * alpha2, p02, p1);
res.c[1] = utils.interval(s2 * alpha2, p3, p2);
res.alpha = alpha2;
res.t = t2;
res.s = s2;
p1 = res.c[0].copy();
p2 = res.c[1].copy();
res.pen = 0;
for (k = utils.mod(i3 + 1, m2); k != j2; k = k1) {
k1 = utils.mod(k + 1, m2);
t2 = utils.tangent(p02, p1, p2, p3, vertex[k], vertex[k1]);
if (t2 < -0.5) {
return 1;
}
pt2 = utils.bezier(t2, p02, p1, p2, p3);
d = utils.ddist(vertex[k], vertex[k1]);
if (d === 0) {
return 1;
}
d1 = utils.dpara(vertex[k], vertex[k1], pt2) / d;
if (Math.abs(d1) > opttolerance) {
return 1;
}
if (utils.iprod(vertex[k], vertex[k1], pt2) < 0 || utils.iprod(vertex[k1], vertex[k], pt2) < 0) {
return 1;
}
res.pen += d1 * d1;
}
for (k = i3; k != j2; k = k1) {
k1 = utils.mod(k + 1, m2);
t2 = utils.tangent(p02, p1, p2, p3, curve2.c[k * 3 + 2], curve2.c[k1 * 3 + 2]);
if (t2 < -0.5) {
return 1;
}
pt2 = utils.bezier(t2, p02, p1, p2, p3);
d = utils.ddist(curve2.c[k * 3 + 2], curve2.c[k1 * 3 + 2]);
if (d === 0) {
return 1;
}
d1 = utils.dpara(curve2.c[k * 3 + 2], curve2.c[k1 * 3 + 2], pt2) / d;
d2 = utils.dpara(curve2.c[k * 3 + 2], curve2.c[k1 * 3 + 2], vertex[k1]) / d;
d2 *= 0.75 * curve2.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 = path2.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, i2, j, r, o = new Opti(), p0, i1, area, alpha, ocurve, s, t;
var convc = new Array(m), areac = new Array(m + 1);
for (i2 = 0; i2 < m; i2++) {
if (curve.tag[i2] == "CURVE") {
convc[i2] = utils.sign(utils.dpara(vert[utils.mod(i2 - 1, m)], vert[i2], vert[utils.mod(i2 + 1, m)]));
} else {
convc[i2] = 0;
}
}
area = 0;
areac[0] = 0;
p0 = curve.vertex[0];
for (i2 = 0; i2 < m; i2++) {
i1 = utils.mod(i2 + 1, m);
if (curve.tag[i1] == "CURVE") {
alpha = curve.alpha[i1];
area += 0.3 * alpha * (4 - alpha) * utils.dpara(curve.c[i2 * 3 + 2], vert[i1], curve.c[i1 * 3 + 2]) / 2;
area += utils.dpara(p0, curve.c[i2 * 3 + 2], curve.c[i1 * 3 + 2]) / 2;
}
areac[i2 + 1] = area;
}
pt[0] = -1;
pen[0] = 0;
len[0] = 0;
for (j = 1; j <= m; j++) {
pt[j] = j - 1;
pen[j] = pen[j - 1];
len[j] = len[j - 1] + 1;
for (i2 = j - 2; i2 >= 0; i2--) {
r = opti_penalty(
path2,
i2,
utils.mod(j, m),
o,
self._params.optTolerance,
convc,
areac
);
if (r) {
break;
}
if (len[j] > len[i2] + 1 || len[j] == len[i2] + 1 && pen[j] > pen[i2] + o.pen) {
pt[j] = i2;
pen[j] = pen[i2] + o.pen;
len[j] = len[i2] + 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 (i2 = om - 1; i2 >= 0; i2--) {
if (pt[j] == j - 1) {
ocurve.tag[i2] = curve.tag[utils.mod(j, m)];
ocurve.c[i2 * 3 + 0] = curve.c[utils.mod(j, m) * 3 + 0];
ocurve.c[i2 * 3 + 1] = curve.c[utils.mod(j, m) * 3 + 1];
ocurve.c[i2 * 3 + 2] = curve.c[utils.mod(j, m) * 3 + 2];
ocurve.vertex[i2] = curve.vertex[utils.mod(j, m)];
ocurve.alpha[i2] = curve.alpha[utils.mod(j, m)];
ocurve.alpha0[i2] = curve.alpha0[utils.mod(j, m)];
ocurve.beta[i2] = curve.beta[utils.mod(j, m)];
s[i2] = t[i2] = 1;
} else {
ocurve.tag[i2] = "CURVE";
ocurve.c[i2 * 3 + 0] = opt[j].c[0];
ocurve.c[i2 * 3 + 1] = opt[j].c[1];
ocurve.c[i2 * 3 + 2] = curve.c[utils.mod(j, m) * 3 + 2];
ocurve.vertex[i2] = utils.interval(
opt[j].s,
curve.c[utils.mod(j, m) * 3 + 2],
vert[utils.mod(j, m)]
);
ocurve.alpha[i2] = opt[j].alpha;
ocurve.alpha0[i2] = opt[j].alpha;
s[i2] = opt[j].s;
t[i2] = opt[j].t;
}
j = pt[j];
}
for (i2 = 0; i2 < om; i2++) {
i1 = utils.mod(i2 + 1, om);
ocurve.beta[i2] = s[i2] / (s[i2] + t[i1]);
}
ocurve.alphaCurve = 1;
path2.curve = ocurve;
}
for (var i = 0; i < this._pathlist.length; i++) {
var path = this._pathlist[i];
calcSums(path);
calcLon(path);
bestPolygon(path);
adjustVertices(path);
if (path.sign === "-") {
reverse(path);
}
smooth(path);
if (self._params.optCurve) {
optiCurve(path);
}
}
},
/**
* Validates some of parameters
* @param params
* @private
*/
_validateParameters: function(params) {
if (params && params.turnPolicy && SUPPORTED_TURNPOLICY_VALUES.indexOf(params.turnPolicy) === -1) {
var goodVals = "'" + SUPPORTED_TURNPOLICY_VALUES.join("', '") + "'";
throw new Error("Bad turnPolicy value. Allowed values are: " + goodVals);
}
if (params && params.threshold != null && params.threshold !== Potrace2.THRESHOLD_AUTO) {
if (typeof params.threshold !== "number" || !utils.between(params.threshold, 0, 255)) {
throw new Error("Bad threshold value. Expected to be an integer in range 0..255");
}
}
if (params && params.optCurve != null && typeof params.optCurve !== "boolean") {
throw new Error("'optCurve' must be Boolean");
}
},
/**
* 本项目新增:直接吃浏览器 ImageData({width,height,data:Uint8ClampedArray}),
* 不再经过 jimp。透明像素按白底合成 —— 与上游 `_processLoadedImage` 的语义一致
* (电商素材多为透明底 PNG,若把 alpha 当黑会整片变实心)。
*/
loadImageData: function(imageData) {
if (!imageData || !imageData.width || !imageData.height || !imageData.data) {
throw new Error("loadImageData: 需要 {width,height,data} 形式的 ImageData");
}
this._imageLoadingIdentifier = null;
this._processLoadedImage(imageData);
},
_processLoadedImage: function(image) {
var src = image.bitmap ? image.bitmap : image;
var width = src.width, height = src.height;
var pixels = src.data;
var bitmap = new Bitmap(width, height);
for (var i = 0, n = width * height; i < n; i++) {
var idx = i * 4;
var opacity = pixels[idx + 3] / 255, r = 255 + (pixels[idx + 0] - 255) * opacity, g = 255 + (pixels[idx + 1] - 255) * opacity, b = 255 + (pixels[idx + 2] - 255) * opacity;
bitmap.data[i] = utils.luminance(r, g, b);
}
this._luminanceData = bitmap;
this._imageLoaded = true;
},
/**
* 上游接口:按路径/Buffer 读图(依赖 jimp)。本内联版**去掉了 jimp**,
* 因此这里只保留签名,改为提示用 `loadImageData`。保留它是为了不破坏上游类型约定,
* 也避免调用方拿到 "Jimp is not defined" 这种莫名其妙的错误。
*/
loadImage: function(target, callback) {
var err = new Error("本内联版 potrace 不支持按路径读图,请改用 loadImageData(imageData)");
if (typeof callback === "function") return callback.call(this, err);
throw err;
},
/**
* Sets algorithm parameters
* @param {Potrace~Options} newParams
*/
setParameters: function(newParams) {
var key, tmpOldVal;
this._validateParameters(newParams);
for (key in this._params) {
if (this._params.hasOwnProperty(key) && newParams.hasOwnProperty(key)) {
tmpOldVal = this._params[key];
this._params[key] = newParams[key];
if (tmpOldVal !== this._params[key] && ["color", "background"].indexOf(key) === -1) {
this._processed = false;
}
}
}
},
/**
* Generates just <path> 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 === Potrace2.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 = '<path d="';
tag += this._pathlist.map(function(path) {
return utils.renderCurve(path.curve, scale);
}).join(" ");
tag += '" stroke="none" fill="' + fillColor + '" fill-rule="evenodd"/>';
return tag;
},
/**
* Returns <symbol> tag. Always has viewBox specified and comes with no fill color,
* so it could be changed with <use> tag
*
* @param id
* @returns {string}
*/
getSymbol: function(id) {
return '<symbol viewBox="0 0 ' + this._luminanceData.width + " " + this._luminanceData.height + '" id="' + id + '">' + this.getPathTag("") + "</symbol>";
},
/**
* 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 '<svg xmlns="http://www.w3.org/2000/svg" width="' + width + '" height="' + height + '" viewBox="0 0 ' + width + " " + height + '" version="1.1">\n' + (this._params.background !== Potrace2.COLOR_TRANSPARENT ? ' <rect x="0" y="0" width="100%" height="100%" fill="' + this._params.background + '" />\n' : "") + " " + this.getPathTag(this._params.color, scale) + "\n</svg>";
}
};
module.exports = Potrace2;
}
});
// image-vectorize/plugin/vendor/potrace/Posterizer.js
var require_Posterizer = __commonJS({
"image-vectorize/plugin/vendor/potrace/Posterizer.js"(exports, module) {
"use strict";
var Potrace2 = require_Potrace();
var utils = require_utils();
function Posterizer2(options) {
this._potrace = new Potrace2();
this._calculatedThreshold = null;
this._params = {
threshold: Potrace2.THRESHOLD_AUTO,
blackOnWhite: true,
steps: Posterizer2.STEPS_AUTO,
background: Potrace2.COLOR_TRANSPARENT,
fillStrategy: Posterizer2.FILL_DOMINANT,
rangeDistribution: Posterizer2.RANGES_AUTO
};
if (options) {
this.setParameters(options);
}
}
for (key in Potrace2) {
if (Object.prototype.hasOwnProperty.call(Potrace2, key) && key === key.toUpperCase()) {
Posterizer2[key] = Potrace2[key];
}
}
var key;
Posterizer2.STEPS_AUTO = -1;
Posterizer2.FILL_SPREAD = "spread";
Posterizer2.FILL_DOMINANT = "dominant";
Posterizer2.FILL_MEDIAN = "median";
Posterizer2.FILL_MEAN = "mean";
Posterizer2.RANGES_AUTO = "auto";
Posterizer2.RANGES_EQUAL = "equal";
Posterizer2.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 !== Posterizer2.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 Posterizer2.FILL_SPREAD:
color = (blackOnWhite ? rangeStart : rangeEnd) + (blackOnWhite ? 1 : -1) * intervalSize * Math.max(0.5, fullRange / 255) * factor;
break;
case Posterizer2.FILL_DOMINANT:
color = histogram.getDominantColor(rangeStart, rangeEnd, utils.clamp(intervalSize, 1, 5));
break;
case Posterizer2.FILL_MEAN:
color = stats.levels.mean;
break;
case Posterizer2.FILL_MEDIAN:
color = stats.levels.median;
break;
}
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 === Posterizer2.RANGES_AUTO ? this._getRangesAuto() : this._getRangesEquallyDistributed();
}
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 === Potrace2.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 === Posterizer2.STEPS_AUTO && this._params.threshold === Potrace2.THRESHOLD_AUTO) {
return 4;
}
var blackOnWhite = this._params.blackOnWhite;
var colorsCount = blackOnWhite ? this._paramThreshold() : 255 - this._paramThreshold();
return steps === Posterizer2.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 !== Potrace2.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 });
var actualPrevLayersOpacity = 0;
return ranges.map(function(colorStop) {
var thisLayerOpacity = colorStop.colorIntensity;
if (thisLayerOpacity === 0) {
return "";
}
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;
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 key2 in this._params) {
if (this._params.hasOwnProperty(key2) && params.hasOwnProperty(key2)) {
this._params[key2] = params[key2];
}
}
this._calculatedThreshold = null;
},
/**
* Returns image as <symbol> 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 '<symbol viewBox="0 0 ' + width + " " + height + '" id="' + id + '">' + paths.join("") + "</symbol>";
},
/**
* 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 = '<svg xmlns="http://www.w3.org/2000/svg" width="' + width + '" height="' + height + '" viewBox="0 0 ' + width + " " + height + '" version="1.1">\n ' + (this._params.background !== Potrace2.COLOR_TRANSPARENT ? '<rect x="0" y="0" width="100%" height="100%" fill="' + this._params.background + '" />\n ' : "") + tags.join("\n ") + "\n</svg>";
return svg.replace(/\n(?:\t*\n)+(\t*)/g, "\n$1");
}
};
module.exports = Posterizer2;
}
});
// image-vectorize/plugin/ui.css
var ui_default = `/* 位图转矢量:全屏模态。深色,与「标注 / 修图」同一套视觉语言。
CSP:由宿主 style-src 'unsafe-inline' 放行,运行时注入 <style>。 */
.vz-root {
position: fixed;
inset: 0;
z-index: 2147483000;
display: flex;
align-items: center;
justify-content: center;
background: rgba(10, 10, 14, 0.72);
font: 13px/1.5 -apple-system, BlinkMacSystemFont, "PingFang SC", "Microsoft YaHei", sans-serif;
color: #e6e6ef;
}
.vz-modal {
display: flex;
flex-direction: column;
width: 100vw;
height: 100vh;
min-width: 0;
min-height: 0;
max-width: none;
background: #1b1b22;
border: 0;
border-radius: 0;
box-shadow: none;
overflow: hidden;
}
/* ---------- 顶栏 ---------- */
.vz-header {
display: flex;
align-items: center;
gap: 10px;
flex: 0 0 auto;
height: 52px;
padding: 0 14px;
background: #202029;
border-bottom: 1px solid #2e2e3a;
}
.vz-title {
font-size: 13px;
font-weight: 500;
color: #f0f0f7;
white-space: nowrap;
}
.vz-title em {
font-style: normal;
color: #8b8b9e;
font-weight: 400;
margin-left: 8px;
}
.vz-title em b {
color: #d6d6e4;
font-weight: 500;
}
.vz-spacer { flex: 1 1 auto; }
.vz-btn {
height: 32px;
padding: 0 14px;
border: 1px solid #3c3c4c;
border-radius: 7px;
background: #2a2a35;
color: #d8d8e4;
font-size: 12px;
cursor: pointer;
white-space: nowrap;
}
.vz-btn:hover { background: #34343f; border-color: #4a4a5c; }
.vz-btn:active { background: #2f2f3a; }
.vz-btn:disabled { opacity: 0.45; cursor: default; }
/* 顶栏「保存为节点 / 复制 SVG / 下载 SVG」三颗走上面这套灰色描边配色。
「关闭」单独用编辑器主色调(.vz-seg 选中态同款 #33566f)填充,与产出操作区分、防误点。
2026-11-19:原「取消」改名「关闭」并按主色调取色(行为不变,仍是 data-act="cancel" 退出编辑器)。 */
.vz-btn-close {
background: #33566f;
border-color: #33566f;
color: #eaf6ff;
}
.vz-btn-close:hover { background: #3d6480; border-color: #4a7394; }
.vz-btn-close:active { background: #2c4a60; }
/* ---------- 主体 ---------- */
.vz-body {
display: flex;
flex: 1 1 auto;
min-height: 0;
}
.vz-preview {
position: relative;
flex: 1 1 auto;
min-width: 0;
display: flex;
align-items: center;
justify-content: center;
padding: 20px;
overflow: hidden;
/* 预览区直接用白底,不铺透明棋盘:描摹结果默认就是「白纸上的单色图形」,
棋盘格既干扰判断形状,也让深色细笔画看起来发虚(实测用户第一反应是「糊」)。
矢量 SVG 本身仍不含背景矩形,导出/复制到 Figma 依旧是透明底。 */
background-color: #ffffff;
/* 缩放 / 平移的**唯一真源**:矢量图与原图两张 img 共用这套变量,
所以按住空格对比时,视图完全不动(各自存一份状态迟早会对不上)。
量纲:zoom 无单位;pan 是**屏幕像素**(先 scale 后 translate,平移量不被缩放放大)。 */
--vz-zoom: 1;
--vz-pan-x: 0px;
--vz-pan-y: 0px;
cursor: grab;
/* 触屏 / 触控板手势全部自己处理,别让浏览器抢去做页面滚动 */
touch-action: none;
}
.vz-preview.is-panning { cursor: grabbing; }
/* 白底之上用一圈极淡的描边 + 细阴影标出画面边界:
白底稿(如菜单/白底商品图)与预览区同色时,否则看不出图到哪里。
绝对定位 + 50%/50% 是为了让 transform 的中心锚点稳定落在预览区正中(缩放锚点计算依赖这一点);
max-* 用 calc(100% - 40px) 抵掉 .vz-preview 的 20px padding(百分比相对 padding box 算)。 */
.vz-stage {
position: absolute;
left: 50%;
top: 50%;
max-width: calc(100% - 40px);
max-height: calc(100% - 40px);
display: block;
box-shadow: 0 1px 3px rgba(0, 0, 0, 0.16), 0 0 0 1px rgba(0, 0, 0, 0.07);
transform:
translate(-50%, -50%)
translate(var(--vz-pan-x), var(--vz-pan-y))
scale(var(--vz-zoom));
transform-origin: 50% 50%;
/* 拖动时每帧改 transform,提前提层,避免整块重绘掉帧(最多两张图,内存代价可忽略) */
will-change: transform;
/* 拖动时别触发 img 的原生拖拽(会拽出一个半透明缩略图,手势直接断掉) */
user-select: none;
-webkit-user-drag: none;
}
.vz-stage[hidden] { display: none; }
/* 白底预览上的常驻小标签:浅色胶囊 + 细描边,深色版本在纯白画面里过于抢眼 */
.vz-badge {
position: absolute;
top: 14px;
left: 14px;
padding: 4px 9px;
border-radius: 6px;
background: rgba(255, 255, 255, 0.92);
border: 1px solid rgba(0, 0, 0, 0.1);
box-shadow: 0 1px 4px rgba(0, 0, 0, 0.08);
color: #55555f;
font-size: 11px;
letter-spacing: 0.2px;
}
.vz-hint {
position: absolute;
bottom: 14px;
left: 50%;
transform: translateX(-50%);
padding: 5px 11px;
border-radius: 999px;
background: rgba(255, 255, 255, 0.92);
border: 1px solid rgba(0, 0, 0, 0.1);
box-shadow: 0 1px 4px rgba(0, 0, 0, 0.08);
color: #55555f;
font-size: 11px;
pointer-events: none;
white-space: nowrap;
}
/* 缩放倍率:只有真的缩放过才出现(100% 时挂 hidden,不占视线)。
它同时是「现在没在 1:1」的唯一视觉信号 —— 用户放大看细节后容易忘记自己还缩着。 */
.vz-zoom {
position: absolute;
right: 14px;
bottom: 14px;
display: flex;
align-items: center;
gap: 6px;
padding: 4px 9px;
border-radius: 6px;
background: rgba(255, 255, 255, 0.94);
border: 1px solid rgba(0, 0, 0, 0.12);
box-shadow: 0 1px 4px rgba(0, 0, 0, 0.1);
color: #45454f;
font-size: 11px;
font-variant-numeric: tabular-nums;
cursor: pointer;
user-select: none;
}
.vz-zoom[hidden] { display: none; }
.vz-zoom b { font-weight: 600; }
.vz-zoom span { color: #9a9aa8; }
.vz-zoom:hover { border-color: rgba(0, 0, 0, 0.22); }
.vz-zoom:hover span { color: #45454f; }
/* 描摹中/出错的浮层 */
.vz-status {
position: absolute;
top: 14px;
right: 14px;
display: flex;
align-items: center;
gap: 8px;
padding: 5px 11px;
border-radius: 7px;
font-size: 11px;
background: rgba(18, 18, 24, 0.88);
border: 1px solid #33333f;
color: #b9b9cc;
}
.vz-status[hidden] { display: none; }
.vz-status.is-busy { color: #ffd08a; border-color: #5a4526; }
.vz-status.is-error { color: #ff9c9c; border-color: #5c2c2c; max-width: 60%; }
.vz-dot {
width: 7px;
height: 7px;
border-radius: 50%;
background: currentColor;
flex: 0 0 auto;
}
.vz-status.is-busy .vz-dot { animation: vz-pulse 1s ease-in-out infinite; }
@keyframes vz-pulse { 0%, 100% { opacity: 0.25; } 50% { opacity: 1; } }
/* ---------- 参数面板 ---------- */
.vz-panel {
flex: 0 0 auto;
width: 312px;
padding: 12px 15px 14px;
background: #1e1e26;
border-left: 1px solid #2e2e3a;
overflow-y: auto;
}
.vz-panel::-webkit-scrollbar { width: 8px; }
.vz-panel::-webkit-scrollbar-thumb { background: #3a3a48; border-radius: 4px; }
/* 组间距比「看着舒服」再紧一点:高级参数默认展开(用户要求),
六组内容在 88vh 里要刚好放得下,否则最后一行「填充 / 背景」会贴着底边被裁 */
.vz-group + .vz-group { margin-top: 12px; padding-top: 10px; border-top: 1px solid #2b2b36; }
.vz-group-title {
font-size: 11px;
color: #7e7e94;
letter-spacing: 0.6px;
margin-bottom: 9px;
text-transform: none;
}
/* 预设 */
.vz-presets {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 7px;
}
.vz-preset {
display: flex;
flex-direction: column;
gap: 2px;
padding: 7px 9px;
border: 1px solid #37374a;
border-radius: 8px;
background: #262631;
color: #d5d5e2;
font-size: 12px;
text-align: left;
cursor: pointer;
}
.vz-preset small {
color: #7b7b91;
font-size: 10px;
line-height: 1.35;
}
.vz-preset:hover { background: #2e2e3b; border-color: #45455a; }
.vz-preset.active {
background: #1f3a30;
border-color: #2f7d5b;
color: #d8ffe9;
}
.vz-preset.active small { color: #79b79b; }
/* 分段控件 */
.vz-row { margin-bottom: 8px; }
/* 按模式隐藏的行(层数只在灰度、阈值只在手动)必须真的消失。
踩过的坑:flex/块级元素上加 \`hidden\` 属性,如果 CSS 里另有 display 声明就会失效,
于是「隐藏」只变成视觉上还在 —— 这里直接 !important 兜住所有形态。 */
.vz-row[hidden] { display: none !important; }
.vz-row:last-child { margin-bottom: 0; }
.vz-row-label {
display: flex;
align-items: center;
justify-content: space-between;
font-size: 12px;
color: #b6b6c8;
margin-bottom: 6px;
}
.vz-row-label span { color: #6f6f85; font-size: 11px; }
.vz-seg {
display: flex;
gap: 0;
border: 1px solid #3a3a4a;
border-radius: 7px;
overflow: hidden;
}
.vz-seg button {
flex: 1 1 0;
height: 28px;
border: 0;
border-right: 1px solid #3a3a4a;
background: #24242e;
color: #a8a8bd;
font-size: 11.5px;
cursor: pointer;
white-space: nowrap;
}
.vz-seg button:last-child { border-right: 0; }
.vz-seg button:hover { background: #2c2c38; color: #d0d0e0; }
.vz-seg button.active { background: #33566f; color: #eaf6ff; }
/* 滑杆 */
.vz-range {
display: flex;
align-items: center;
gap: 9px;
}
.vz-range input[type="range"] {
flex: 1 1 auto;
min-width: 0;
height: 4px;
-webkit-appearance: none;
appearance: none;
background: #3a3a4a;
border-radius: 2px;
outline: none;
}
.vz-range input[type="range"]::-webkit-slider-thumb {
-webkit-appearance: none;
appearance: none;
width: 13px;
height: 13px;
border-radius: 50%;
background: #cfcfdd;
border: 0;
cursor: pointer;
}
.vz-range input[type="range"]:disabled { opacity: 0.4; }
.vz-range input[type="range"]:disabled::-webkit-slider-thumb { cursor: default; }
.vz-range-val {
flex: 0 0 auto;
min-width: 34px;
text-align: right;
font-size: 11.5px;
color: #d0d0e0;
font-variant-numeric: tabular-nums;
}
/* 高级参数折叠:首屏只露高频项,低频参数收起来但一档可达 */
.vz-adv-toggle {
display: flex;
align-items: center;
justify-content: space-between;
width: 100%;
height: 30px;
padding: 0 10px;
border: 1px solid #37374a;
border-radius: 7px;
background: #24242e;
color: #a8a8bd;
font-size: 11.5px;
cursor: pointer;
}
.vz-adv-toggle:hover { background: #2c2c38; color: #d0d0e0; }
.vz-adv-toggle span { color: #6f6f85; }
/* 单色填充色(仅「纯单色」生效)。原生 color input 在深色面板里默认边框很亮,
去掉内边距与外框,只留一块颜色本身,和滑杆行视觉一致 */
.vz-color {
flex: 0 0 auto;
width: 42px;
height: 22px;
padding: 0;
border: 1px solid #45455a;
border-radius: 6px;
background: transparent;
cursor: pointer;
}
.vz-color::-webkit-color-swatch-wrapper { padding: 2px; }
.vz-color::-webkit-color-swatch { border: none; border-radius: 4px; }
.vz-color:disabled { cursor: default; }
/* 填充 / 背景并排(用户要求放一排)+ 「带底」小勾选。
色块从 42px 收到 34px,两个并排仍能塞进 312px 面板且不挤掉标签。 */
.vz-swatches {
display: flex;
align-items: center;
gap: 6px;
flex: 0 0 auto;
}
.vz-swatches .vz-color { width: 34px; }
.vz-mini {
display: inline-flex;
align-items: center;
gap: 4px;
height: 22px;
padding: 0 6px;
border: 1px solid #3c3c4c;
border-radius: 6px;
background: #24242e;
color: #a8a8bd;
font-size: 11px;
white-space: nowrap;
cursor: pointer;
}
.vz-mini:hover { border-color: #4a4a5c; color: #d0d0e0; }
.vz-mini input {
width: 11px;
height: 11px;
margin: 0;
accent-color: #2f9c69;
cursor: pointer;
}
/* 勾选开关(按孤岛拆分):原生 checkbox 在深色面板里太小、且难以点中。
用 label 包一层,点整块都能切换;focus-visible 保留键盘可达的焦点环。 */
.vz-row-switch {
display: flex;
align-items: center;
justify-content: space-between;
gap: 12px;
}
.vz-row-text {
display: flex;
flex-direction: column;
gap: 3px;
min-width: 0;
font-size: 12px;
color: #b6b6c8;
}
.vz-row-text span {
color: #6f6f85;
font-size: 10.5px;
line-height: 1.4;
}
.vz-switch {
position: relative;
flex: 0 0 auto;
width: 34px;
height: 20px;
cursor: pointer;
}
.vz-switch input {
position: absolute;
inset: 0;
width: 100%;
height: 100%;
margin: 0;
opacity: 0;
cursor: pointer;
}
.vz-switch i {
position: absolute;
inset: 0;
border-radius: 999px;
background: #3a3a4a;
transition: background 0.15s ease;
pointer-events: none;
}
.vz-switch i::after {
content: '';
position: absolute;
top: 2px;
left: 2px;
width: 16px;
height: 16px;
border-radius: 50%;
background: #b9b9c9;
transition: transform 0.15s ease, background 0.15s ease;
}
.vz-switch input:checked + i { background: #2f7d5b; }
.vz-switch input:checked + i::after { transform: translateX(14px); background: #ffffff; }
.vz-switch input:focus-visible + i { box-shadow: 0 0 0 2px rgba(90, 200, 160, 0.45); }
.vz-adv { margin-top: 10px; }
.vz-adv[hidden] { display: none; }
/* 统计 */
.vz-stats {
display: flex;
gap: 14px;
flex-wrap: wrap;
font-size: 11.5px;
color: #8f8fa4;
}
.vz-stats b { color: #d8d8e6; font-weight: 500; }
.vz-note {
margin-top: 9px;
font-size: 10.5px;
line-height: 1.55;
color: #6b6b80;
}
/* 窄屏:面板转到底部 */
@media (max-width: 900px) {
.vz-modal { width: 100vw; height: 100vh; min-width: 0; }
.vz-body { flex-direction: column; }
.vz-panel { width: auto; max-height: 46%; border-left: 0; border-top: 1px solid #2e2e3a; }
}
`;
// image-vectorize/plugin/engine.js
var import_Potrace = __toESM(require_Potrace());
var import_Posterizer = __toESM(require_Posterizer());
// image-vectorize/plugin/islands.js
var TOKEN = /[MLCZ]|-?\d*\.?\d+(?:e[-+]?\d+)?/gi;
var EPS = 1e-6;
function sampleCubic(poly, p0, p1, p2, p3) {
const steps = 4;
for (let k = 1; k <= steps; k++) {
const t = k / steps;
const mt = 1 - t;
const a = mt * mt * mt;
const b = 3 * mt * mt * t;
const c = 3 * mt * t * t;
const d = t * t * t;
poly.push([
a * p0[0] + b * p1[0] + c * p2[0] + d * p3[0],
a * p0[1] + b * p1[1] + c * p2[1] + d * p3[1]
]);
}
}
function bboxOf(poly) {
let x0 = Infinity;
let y0 = Infinity;
let x1 = -Infinity;
let y1 = -Infinity;
for (let i = 0; i < poly.length; i++) {
const p = poly[i];
if (p[0] < x0) x0 = p[0];
if (p[0] > x1) x1 = p[0];
if (p[1] < y0) y0 = p[1];
if (p[1] > y1) y1 = p[1];
}
return { x0, y0, x1, y1 };
}
function shoelace(poly) {
let sum = 0;
for (let i = 0, n = poly.length; i < n; i++) {
const a = poly[i];
const b = poly[(i + 1) % n];
sum += a[0] * b[1] - b[0] * a[1];
}
return sum / 2;
}
function bboxContains(outer, inner) {
return inner.x0 >= outer.x0 - EPS && inner.x1 <= outer.x1 + EPS && inner.y0 >= outer.y0 - EPS && inner.y1 <= outer.y1 + EPS;
}
function pointInPoly(pt, poly) {
let inside = false;
for (let i = 0, j = poly.length - 1; i < poly.length; j = i++) {
const xi = poly[i][0];
const yi = poly[i][1];
const xj = poly[j][0];
const yj = poly[j][1];
if (yi > pt[1] !== yj > pt[1] && pt[0] < (xj - xi) * (pt[1] - yi) / (yj - yi) + xi) inside = !inside;
}
return inside;
}
function parseSubpaths(d) {
const tokens = String(d || "").match(TOKEN);
const subs = [];
if (!tokens || !tokens.length) return subs;
const isNum = (k) => k < tokens.length && !/^[MLCZ]$/i.test(tokens[k]);
const at = (k) => isNum(k) ? Number(tokens[k]) : NaN;
let cur = null;
let last = [0, 0];
let i = 0;
while (i < tokens.length) {
const tok = tokens[i];
const cmd = tok.length === 1 ? tok.toUpperCase() : "";
if (cmd === "M") {
const x = at(i + 1);
const y = at(i + 2);
if (!Number.isFinite(x) || !Number.isFinite(y)) break;
i += 3;
cur = { d: "M " + x + " " + y, poly: [[x, y]] };
subs.push(cur);
last = [x, y];
continue;
}
if (!cur) {
i += 1;
continue;
}
if (cmd === "C") {
const p1 = [at(i + 1), at(i + 2)];
const p2 = [at(i + 3), at(i + 4)];
const p3 = [at(i + 5), at(i + 6)];
if (!p1.concat(p2, p3).every(Number.isFinite)) break;
i += 7;
cur.d += " C " + p1[0] + " " + p1[1] + ", " + p2[0] + " " + p2[1] + ", " + p3[0] + " " + p3[1];
sampleCubic(cur.poly, last, p1, p2, p3);
last = p3;
continue;
}
if (cmd === "L") {
const p1 = [at(i + 1), at(i + 2)];
if (!Number.isFinite(p1[0]) || !Number.isFinite(p1[1])) break;
const p2 = [at(i + 3), at(i + 4)];
if (Number.isFinite(p2[0]) && Number.isFinite(p2[1])) {
i += 5;
cur.d += " L " + p1[0] + " " + p1[1] + " " + p2[0] + " " + p2[1];
cur.poly.push(p1, p2);
last = p2;
} else {
i += 3;
cur.d += " L " + p1[0] + " " + p1[1];
cur.poly.push(p1);
last = p1;
}
continue;
}
if (cmd === "Z") {
i += 1;
cur.d += " Z";
continue;
}
i += 1;
}
const out = [];
for (const s of subs) {
if (s.poly.length < 3) continue;
const area = Math.abs(shoelace(s.poly));
if (!(area > EPS)) continue;
s.bbox = bboxOf(s.poly);
s.area = area;
out.push(s);
}
return out;
}
function groupSubpaths(subs) {
const n = subs.length;
const parent = new Array(n).fill(-1);
const order = subs.map((s, i) => i).sort((a, b) => subs[b].area - subs[a].area);
for (let k = 0; k < n; k++) {
const ci = order[k];
for (let j = k - 1; j >= 0; j--) {
const pi = order[j];
if (!bboxContains(subs[pi].bbox, subs[ci].bbox)) continue;
if (!pointInPoly(subs[ci].poly[0], subs[pi].poly)) continue;
parent[ci] = pi;
break;
}
}
const depth = new Array(n).fill(0);
const resolveDepth = (i) => {
const stack = [];
let c = i;
while (parent[c] >= 0 && depth[c] === 0 && stack.indexOf(c) < 0) {
stack.push(c);
c = parent[c];
}
let base = depth[c];
for (let k = stack.length - 1; k >= 0; k--) {
base += 1;
depth[stack[k]] = base;
}
return depth[i];
};
for (let i = 0; i < n; i++) resolveDepth(i);
const groups = /* @__PURE__ */ new Map();
for (let i = 0; i < n; i++) {
let c = i;
let guard = 0;
while (depth[c] % 2 === 1 && parent[c] >= 0 && guard++ < 512) c = parent[c];
if (!groups.has(c)) groups.set(c, []);
groups.get(c).push(i);
}
const out = [];
groups.forEach((idxs, root) => {
idxs.sort((a, b) => a - b);
out.push({ root, idxs, area: subs[root].area });
});
return out;
}
function splitPathData(d) {
const subs = parseSubpaths(d);
if (subs.length <= 1) return subs.length ? [d] : [];
const groups = groupSubpaths(subs);
if (groups.length <= 1) return [d];
groups.sort((a, b) => b.area - a.area);
return groups.map((g) => g.idxs.map((i) => subs[i].d).join(" "));
}
function splitSvgIslands(svg) {
const text = String(svg || "");
let elements = 0;
let islands = 0;
const out = text.replace(/<path\b([^>]*?)\/?>/g, (whole, attrs) => {
const dMatch = /\bd="([^"]*)"/.exec(attrs);
if (!dMatch) {
elements += 1;
islands += 1;
return whole;
}
const parts = splitPathData(dMatch[1]);
if (!parts.length) return whole;
const rest = attrs.replace(/\bd="[^"]*"/, "").replace(/\s+/g, " ").trim();
const tail = rest ? " " + rest : "";
elements += parts.length;
islands += parts.length;
return parts.map((p) => '<path d="' + p + '"' + tail + "/>").join("\n ");
});
return { svg: out, elements, islands };
}
function countIslands(svg) {
const re = /<path\b[^>]*\bd="([^"]*)"/g;
let m;
let total = 0;
while (m = re.exec(String(svg || ""))) {
const subs = parseSubpaths(m[1]);
total += subs.length <= 1 ? 1 : groupSubpaths(subs).length;
}
return total;
}
// image-vectorize/plugin/engine.js
var LEVELS_MIN = 2;
var LEVELS_MAX = 5;
var MAX_TRACE_SIDE = 3e3;
var DEFAULTS = {
mode: "gray",
// 'gray' 灰度分层 / 'mono' 纯单色
levels: 3,
// 灰度层数(2–5,仅 gray)
threshold: -1,
// -1 = 自动(两种模式都支持)
turdSize: 3,
// 去小点:面积小于它的碎片直接丢(毛刺/噪点克星)
alphaMax: 1,
// 拐角阈值:0 全折线、1 默认、1.334 最圆
// 曲线拟合容差(越小越贴合原图像素边缘,路径数据也越大)。
// 上游默认 0.2 是「视觉上够用」的省数据值;实测 0.2 在文字笔画与圆角处会
// 吃掉约半个像素的弯折,所以这里默认降到 0.05(用户 2026-11-05 要求「边缘精度再高一点」)。
optTolerance: 0.05,
invert: false,
// 反相:描摹亮部(黑底白字场景)
color: "#1a1a1a",
// mono 的填充色
// 背景色:默认白 —— 预览区直接铺白纸,不铺透明棋盘(用户 2026-11-05 要求)。
// 它**默认只当预览底**,导出仍是透明 SVG(粘到 Figma 不会多一个背景图层);
// 想要导出也带底,用户勾「带底」(bgExport)即可。
bg: "#ffffff",
bgExport: false,
outScale: 1,
// 输出尺寸倍率(只放大尺寸,不重算曲线)
// 按孤岛拆分:potrace 出厂把整图所有轮廓塞进一个 path,粘到 Figma 只是一个整体;
// 拆开后每个不连通的图形都是独立 path,可以单独选中/移动(用户 2026-11-05 要求)。
// 默认开 —— 需求来源就是「现在是一个整体,我想分开」。
splitIslands: true
};
var TOLERANCE_TONES = { fine: 0.05, normal: 0.15, light: 0.4 };
var clampInt = (v, min, max, dflt) => {
const n = Math.round(Number(v));
return Number.isFinite(n) ? Math.min(max, Math.max(min, n)) : dflt;
};
function normalizeParams(p) {
const src = p || {};
return {
mode: src.mode === "mono" ? "mono" : "gray",
levels: clampInt(src.levels, LEVELS_MIN, LEVELS_MAX, DEFAULTS.levels),
threshold: Number(src.threshold) >= 0 ? clampInt(src.threshold, 0, 255, 128) : -1,
turdSize: clampInt(src.turdSize, 0, 64, DEFAULTS.turdSize),
alphaMax: (() => {
const n = Number(src.alphaMax);
return Number.isFinite(n) ? Math.min(1.334, Math.max(0, n)) : DEFAULTS.alphaMax;
})(),
optTolerance: (() => {
const n = Number(src.optTolerance);
return Number.isFinite(n) ? Math.min(2, Math.max(0.01, n)) : DEFAULTS.optTolerance;
})(),
invert: Boolean(src.invert),
color: /^#[0-9a-f]{6}$/i.test(String(src.color || "")) ? String(src.color) : DEFAULTS.color,
bg: /^#[0-9a-f]{6}$/i.test(String(src.bg || "")) ? String(src.bg) : DEFAULTS.bg,
bgExport: src.bgExport === void 0 ? DEFAULTS.bgExport : Boolean(src.bgExport),
outScale: Math.min(4, Math.max(1, Number(src.outScale) || 1)),
splitIslands: src.splitIslands === void 0 ? DEFAULTS.splitIslands : Boolean(src.splitIslands)
};
}
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;
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 [];
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 out2 = [];
for (let k = 1; k < levels; k++) out2.push(Math.round(255 * k / levels));
return out2;
}
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;
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;
}
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 import_Potrace.default({
threshold: p.threshold >= 0 ? p.threshold : import_Potrace.default.THRESHOLD_AUTO,
turdSize: p.turdSize,
alphaMax: p.alphaMax,
optCurve: true,
optTolerance: p.optTolerance,
blackOnWhite: !p.invert,
color: p.color
});
potrace.loadImageData(imageData);
svg = potrace.getSVG();
} else {
const cuts = quantileThresholds(imageData, p.levels);
levels = cuts.length + 1;
const posterizer = new import_Posterizer.default({
// 传数组 ⇒ 跳过上游的直方图多级阈值搜索(那玩意 5 层要 28s)
steps: cuts.length ? cuts : [128],
threshold: p.threshold >= 0 ? p.threshold : import_Potrace.default.THRESHOLD_AUTO,
turdSize: p.turdSize,
alphaMax: p.alphaMax,
optCurve: true,
optTolerance: p.optTolerance,
blackOnWhite: !p.invert,
fillStrategy: "median",
// 灰度:每层取该层亮度中位数
color: "#000000"
// 灰度靠 fill-opacity 叠出来,底色固定黑
});
posterizer.loadImageData(imageData);
svg = posterizer.getSVG();
}
let elements = (String(svg).match(/<path/g) || []).length;
let islands = 0;
if (p.splitIslands) {
const split = splitSvgIslands(svg);
svg = split.svg;
elements = split.elements;
islands = split.islands;
} else {
islands = countIslands(svg) || elements;
}
if (p.bgExport) {
svg = svg.replace(/<svg\b[^>]*>/i, function(tag) {
return tag + '\n<rect width="100%" height="100%" fill="' + p.bg + '"/>';
});
}
return { svg, ms: Math.round(now() - t0), paths: elements, elements, islands, levels };
}
// image-vectorize/plugin/trace.js
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 = dataUrl;
});
}
function prepareSource(img) {
const srcW = img.naturalWidth || img.width;
const srcH = img.naturalHeight || img.height;
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 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 };
}
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.src = url;
});
}
async function svgToPngBlob(svg, baseW, baseH, outScale) {
const img = await svgToImage(svg);
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 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);
else reject(new Error("PNG 编码失败"));
}, "image/png");
});
}
function svgStats(svg) {
const text = String(svg);
const paths = (text.match(/<path/g) || []).length;
const fills = [];
const re = /fill="([^"]+)"/g;
let m;
while (m = re.exec(text)) if (fills.indexOf(m[1]) < 0) fills.push(m[1]);
return { paths, colors: fills.length, bytes: text.length };
}
// image-vectorize/plugin/ui.js
var SETTING_KEYS = ["preset", "mode", "levels", "threshold", "turdSize", "alphaMax", "optTolerance", "invert", "color", "bg", "bgExport", "outScale", "advOpen", "splitIslands"];
var 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 }
};
var HINTS = {
turdSize: "抹掉小于该像素面积的碎片(毛刺 / 噪点)",
alphaMax: "越小越硬朗(多折线),越大越圆"
};
function esc(s) {
return String(s).replace(/[&<>"']/g, function(c) {
return { "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;", "'": "&#39;" }[c];
});
}
function segHTML(group, options, current) {
return options.map(function(pair) {
const active = String(pair[0]) === String(current) ? " active" : "";
return '<button type="button" class="' + active.trim() + '" data-seg="' + group + '" data-value="' + pair[0] + '">' + esc(pair[1]) + "</button>";
}).join("");
}
function rangeHTML(name, label, min, max, step, value, hint) {
return '<div class="vz-row"><div class="vz-row-label">' + esc(label) + (hint ? "<span>" + esc(hint) + "</span>" : "") + '</div><div class="vz-range"><input type="range" data-param="' + name + '" min="' + min + '" max="' + max + '" step="' + step + '" value="' + value + '"><span class="vz-range-val" data-val="' + name + '">' + value + "</span></div></div>";
}
function panelHTML(params, preset, outScale, advOpen) {
const presets = Object.keys(PRESETS).map(function(key) {
const p = PRESETS[key];
return '<button type="button" class="vz-preset' + (key === preset ? " active" : "") + '" data-preset="' + key + '">' + esc(p.label) + "<small>" + esc(p.hint) + "</small></button>";
}).join("");
return '<div class="vz-group"><div class="vz-group-title">预设</div><div class="vz-presets">' + presets + '</div></div><div class="vz-group"><div class="vz-row"><div class="vz-row-label">描摹方式</div><div class="vz-seg" data-seg-group="mode">' + segHTML("mode", [["gray", "灰度分层"], ["mono", "纯单色"]], params.mode) + '</div></div><div class="vz-row" data-only="gray"><div class="vz-row-label">层数<span>多一层,浅色块更容易分离</span></div><div class="vz-seg" data-seg-group="levels">' + [2, 3, 4, 5].map(function(n) {
return '<button type="button" data-seg="levels" data-value="' + n + '">' + n + "</button>";
}).join("") + '</div></div></div><div class="vz-group">' + rangeHTML("turdSize", "去小点", 0, 40, 1, params.turdSize, HINTS.turdSize) + '<div class="vz-row"><div class="vz-row-label">边缘<span>拐角处理</span></div><div class="vz-seg" data-seg-group="alphaTone"><button type="button" data-seg="alphaTone" data-value="hard">硬朗</button><button type="button" data-seg="alphaTone" data-value="normal">标准</button><button type="button" data-seg="alphaTone" data-value="round">圆润</button></div></div><div class="vz-row"><div class="vz-row-label">精度<span>越高越贴合原图,曲线数据略多</span></div><div class="vz-seg" data-seg-group="precision"><button type="button" data-seg="precision" data-value="fine">精细</button><button type="button" data-seg="precision" data-value="normal">标准</button><button type="button" data-seg="precision" data-value="light">轻量</button></div></div></div><div class="vz-group"><div class="vz-row"><div class="vz-row-label">输出倍率<span>PNG 按矢量重绘,真清晰</span></div><div class="vz-seg" data-seg-group="outScale">' + [1, 2, 3, 4].map(function(n) {
return '<button type="button" data-seg="outScale" data-value="' + n + '">' + n + "×</button>";
}).join("") + '</div></div><div class="vz-row vz-row-switch"><div class="vz-row-text">按孤岛拆分<span>每个连通块一个图层,粘到 Figma 可单独选中;笔画不连的汉字会分成几块</span></div><label class="vz-switch"><input type="checkbox" data-check="splitIslands"' + (params.splitIslands ? " checked" : "") + '><i></i></label></div></div><div class="vz-group"><div class="vz-stats"><span><b data-stat="elements">–</b> 元素</span><span><b data-stat="levels">–</b> 层</span><span><b data-stat="bytes">–</b></span><span><b data-stat="ms">–</b></span></div></div><div class="vz-group"><button type="button" class="vz-adv-toggle" data-act="adv" aria-expanded="' + (advOpen ? "true" : "false") + '">高级参数<span data-adv-caret>' + (advOpen ? "▴" : "▾") + '</span></button><div class="vz-adv" data-adv' + (advOpen ? "" : " hidden") + '><div class="vz-row"><div class="vz-row-label">阈值<span>自动按直方图取,手动可救极端图</span></div><div class="vz-seg" data-seg-group="thrMode"><button type="button" data-seg="thrMode" data-value="auto">自动</button><button type="button" data-seg="thrMode" data-value="manual">手动</button></div></div><div data-thr-row hidden>' + rangeHTML("threshold", "阈值取值", 0, 255, 1, params.threshold >= 0 ? params.threshold : 128, "") + '</div><div class="vz-row"><div class="vz-row-label">反相<span>黑底白字时打开</span></div><div class="vz-seg" data-seg-group="invert">' + segHTML("invert", [["0", "正片"], ["1", "负片"]], params.invert ? 1 : 0) + '</div></div><div class="vz-row"><div class="vz-row-label">填充 / 背景<span>填充仅「纯单色」生效 · 背景作预览底</span></div><div class="vz-swatches"><input type="color" class="vz-color" data-color="color" value="' + esc(params.color) + '" title="填充色(纯单色生效)"><input type="color" class="vz-color" data-color="bg" value="' + esc(params.bg) + '" title="背景色(预览底;勾「带底」写入导出)"><label class="vz-mini" title="导出 / 复制时把背景色一起写进 SVG(默认不带,粘到 Figma 是透明底)"><input type="checkbox" data-check="bgExport"' + (params.bgExport ? " checked" : "") + "><span>带底</span></label></div></div></div></div>";
}
function viewHTML(name) {
return '<div class="vz-root"><div class="vz-modal" role="dialog" aria-modal="true" aria-label="位图转矢量"><header class="vz-header"><span class="vz-title">位图转矢量<em data-meta>' + esc(name) + '</em></span><div class="vz-spacer"></div><button type="button" class="vz-btn" data-act="save">保存为节点</button><button type="button" class="vz-btn" data-act="copy">复制 SVG</button><button type="button" class="vz-btn" data-act="svg">下载 SVG</button><button type="button" class="vz-btn vz-btn-close" data-act="cancel">关闭</button></header><div class="vz-body"><div class="vz-preview" data-preview><img class="vz-stage" data-stage="vector" alt="矢量预览" draggable="false"><img class="vz-stage" data-stage="original" alt="原图" draggable="false" hidden><div class="vz-badge" data-badge>矢量预览</div><div class="vz-status" data-status hidden><i class="vz-dot"></i><span data-status-text></span></div><div class="vz-hint">空格 对比原图 · 滚轮缩放 · 拖动平移 · 双击复位</div><div class="vz-zoom" data-zoom-chip hidden title="点击回到 100%"><b data-zoom-val>100%</b><span>复位</span></div></div><aside class="vz-panel" data-panel></aside></div></div></div>';
}
var ALPHA_TONE = { hard: 0.4, normal: 1, round: 1.2 };
var toneOf = (alphaMax) => alphaMax <= 0.6 ? "hard" : alphaMax >= 1.1 ? "round" : "normal";
var tolToneOf = (tol) => tol <= 0.08 ? "fine" : tol >= 0.3 ? "light" : "normal";
function createVectorizer(options) {
const settings = options.settings;
const onSaveNode = options.onSaveNode;
const onError = options.onError;
const onClose = options.onClose;
let root = null;
let els = null;
let source = null;
let params = normalizeParams(DEFAULTS);
let preset = "text";
let outScale = 2;
let advOpen = true;
let currentSvg = "";
let lastElements = 0;
let lastIslands = 0;
let currentBlobUrl = "";
let seq = 0;
let debounceTimer = 0;
let spaceDown = false;
let zoom = 1;
let panX = 0;
let panY = 0;
let drag = null;
function readSettings() {
const out = {};
if (!settings || typeof settings.get !== "function") return out;
for (const key of SETTING_KEYS) {
let value;
try {
value = settings.get(key);
} catch (e) {
continue;
}
if (value === void 0 || value === null || value === "") continue;
if (key === "invert" || key === "bgExport") value = value === true || value === "true" || value === 1 || value === "1";
if (key === "splitIslands") value = !(value === false || value === "false" || value === 0 || value === "0");
if (key === "advOpen") value = !(value === false || value === "false" || value === 0 || value === "0");
out[key] = value;
}
return out;
}
function writeSettings() {
if (!settings || typeof settings.set !== "function") return;
try {
settings.set("preset", preset);
settings.set("mode", params.mode);
settings.set("levels", params.levels);
settings.set("threshold", params.threshold);
settings.set("turdSize", params.turdSize);
settings.set("alphaMax", params.alphaMax);
settings.set("optTolerance", params.optTolerance);
settings.set("invert", params.invert);
settings.set("color", params.color);
settings.set("bg", params.bg);
settings.set("bgExport", params.bgExport);
settings.set("outScale", outScale);
settings.set("advOpen", advOpen);
settings.set("splitIslands", params.splitIslands);
} catch (e) {
}
}
function setStatus(kind, text) {
if (!els) return;
const box = els.status;
if (!kind) {
box.hidden = true;
box.className = "vz-status";
return;
}
box.hidden = false;
box.className = "vz-status is-" + kind;
els.statusText.textContent = text || "";
}
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("elements", "–");
put("levels", "–");
put("bytes", "–");
put("ms", "–");
return;
}
const elements = stats.elements === void 0 ? stats.paths : stats.elements;
put("elements", stats.islands && stats.islands !== elements ? elements + "(" + stats.islands + " 孤岛合并)" : String(elements));
put("levels", String(levels || 1));
put("bytes", stats.bytes >= 1024 * 1024 ? (stats.bytes / 1024 / 1024).toFixed(1) + "MB" : Math.round(stats.bytes / 1024) + "KB");
put("ms", ms === void 0 || ms === null ? "–" : ms + "ms");
}
function syncControls() {
if (!els) return;
const panel = els.panel;
panel.querySelectorAll("[data-preset]").forEach(function(btn) {
btn.classList.toggle("active", btn.dataset.preset === preset);
});
panel.querySelectorAll("[data-param]").forEach(function(input) {
const key = input.dataset.param;
input.value = key === "threshold" && params.threshold < 0 ? 128 : params[key];
const out = panel.querySelector('[data-val="' + key + '"]');
if (out) out.textContent = input.value;
});
panel.querySelectorAll('[data-only="gray"]').forEach(function(row) {
row.hidden = params.mode !== "gray";
});
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="precision"] button').forEach(function(btn) {
btn.classList.toggle("active", btn.dataset.value === tolToneOf(params.optTolerance));
});
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);
});
panel.querySelectorAll("[data-check]").forEach(function(input) {
input.checked = Boolean(params[input.dataset.check]);
});
const thrRow = panel.querySelector("[data-thr-row]");
if (thrRow) thrRow.hidden = params.threshold < 0;
panel.querySelectorAll("[data-color]").forEach(function(input) {
const key = input.dataset.color;
input.value = key === "bg" ? params.bg : params.color;
const locked = key === "color" && params.mode !== "mono";
input.disabled = locked;
input.style.opacity = locked ? "0.45" : "";
});
applyPreviewBg();
}
function applyPreviewBg() {
if (!els || !els.preview) return;
els.preview.style.backgroundColor = params.bg;
}
function releasePreview() {
if (currentBlobUrl) {
URL.revokeObjectURL(currentBlobUrl);
currentBlobUrl = "";
}
}
function showVector(svg) {
if (!els) return;
releasePreview();
const blob = new Blob([svg], { type: "image/svg+xml;charset=utf-8" });
currentBlobUrl = URL.createObjectURL(blob);
els.vector.src = currentBlobUrl;
els.vector.hidden = false;
updateBadge();
}
function updateBadge() {
if (!els) return;
els.vector.hidden = spaceDown;
els.original.hidden = !spaceDown;
els.badge.textContent = spaceDown ? "原图" : "矢量预览";
}
const ZOOM_MIN = 0.2;
const ZOOM_MAX = 8;
function applyView() {
if (!els || !els.preview) return;
els.preview.style.setProperty("--vz-zoom", String(zoom));
els.preview.style.setProperty("--vz-pan-x", panX + "px");
els.preview.style.setProperty("--vz-pan-y", panY + "px");
const changed = zoom !== 1 || panX !== 0 || panY !== 0;
if (els.zoomVal) els.zoomVal.textContent = Math.round(zoom * 100) + "%";
if (els.zoomChip) els.zoomChip.hidden = !changed;
}
function resetView() {
zoom = 1;
panX = 0;
panY = 0;
drag = null;
if (els && els.preview) els.preview.classList.remove("is-panning");
applyView();
}
function zoomAt(clientX, clientY, factor) {
if (!els || !els.preview) return;
const next = Math.min(ZOOM_MAX, Math.max(ZOOM_MIN, zoom * factor));
if (Math.abs(next - zoom) < 1e-4) return;
const rect = els.preview.getBoundingClientRect();
const dx = (clientX - (rect.left + rect.width / 2) - panX) / zoom;
const dy = (clientY - (rect.top + rect.height / 2) - panY) / zoom;
panX -= dx * (next - zoom);
panY -= dy * (next - zoom);
zoom = next;
applyView();
}
function zoomAtCenter(factor) {
if (!els || !els.preview) return;
const rect = els.preview.getBoundingClientRect();
zoomAt(rect.left + rect.width / 2, rect.top + rect.height / 2, factor);
}
function onPreviewWheel(event) {
event.preventDefault();
if (Math.abs(event.deltaX) > Math.abs(event.deltaY)) {
panX += event.deltaX;
applyView();
return;
}
if (!event.deltaY) return;
const step = event.ctrlKey ? 0.01 : Math.abs(event.deltaY) >= 40 ? 18e-4 : 0.012;
zoomAt(event.clientX, event.clientY, Math.exp(-event.deltaY * step));
}
function onPreviewPointerDown(event) {
if (!els || !els.preview) return;
if (event.button !== 0 && event.button !== 1) return;
if (event.target.closest(".vz-zoom")) return;
event.preventDefault();
drag = { x: event.clientX, y: event.clientY, panX, panY, id: event.pointerId };
els.preview.classList.add("is-panning");
try {
els.preview.setPointerCapture(event.pointerId);
} catch (e) {
}
}
function onPreviewPointerMove(event) {
if (!drag || !els || !els.preview || event.pointerId !== drag.id) return;
panX = drag.panX + (event.clientX - drag.x);
panY = drag.panY + (event.clientY - drag.y);
applyView();
}
function onPreviewPointerUp(event) {
if (!drag) return;
if (event && event.pointerId !== void 0 && event.pointerId !== drag.id) return;
if (els && els.preview) {
els.preview.classList.remove("is-panning");
try {
els.preview.releasePointerCapture(drag.id);
} catch (e) {
}
}
drag = null;
}
function onPreviewDblClick(event) {
if (event.target.closest(".vz-zoom")) return;
resetView();
}
function retrace() {
if (!source) return;
const ticket = ++seq;
try {
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;
currentSvg = out.svg;
showVector(currentSvg);
const stats = svgStats(currentSvg);
stats.elements = out.elements;
stats.islands = out.islands;
lastElements = out.elements;
lastIslands = out.islands;
setStats(stats, 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 if (params.mode === "gray" && params.splitIslands && out.elements > 40) {
setStatus("busy", "灰度按层各拆一遍(" + out.elements + " 个元素,层间会重叠);要干净分离改用「纯单色」");
window.setTimeout(function() {
if (ticket === seq) setStatus(null);
}, 4200);
}
els.meta.textContent = source.name + " · " + prepared.srcW + "×" + prepared.srcH;
} catch (error) {
if (ticket !== seq) return;
currentSvg = "";
setStats(null);
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();
}, 120);
}
async function writeSvgToClipboard(svgText) {
const nav = typeof navigator === "undefined" ? null : navigator;
const Item = typeof window === "undefined" ? null : window.ClipboardItem;
const plain = new Blob([svgText], { type: "text/plain" });
const html = new Blob([svgText], { type: "text/html" });
let svgFlavor = false;
if (nav && nav.clipboard && typeof nav.clipboard.write === "function" && typeof Item === "function") {
try {
svgFlavor = typeof Item.supports !== "function" || Item.supports("image/svg+xml");
} catch (e) {
svgFlavor = false;
}
const tryWrite = async function(withSvg) {
const flavors = { "text/plain": plain, "text/html": html };
if (withSvg) flavors["image/svg+xml"] = new Blob([svgText], { type: "image/svg+xml" });
await nav.clipboard.write([new Item(flavors)]);
};
try {
await tryWrite(svgFlavor);
return svgFlavor ? "svg" : "text";
} catch (error) {
if (svgFlavor) {
try {
await tryWrite(false);
return "text";
} catch (error2) {
}
}
}
}
if (nav && nav.clipboard && typeof nav.clipboard.writeText === "function") {
await nav.clipboard.writeText(svgText);
return "text";
}
return "";
}
async function copySvg(button) {
if (!currentSvg) {
setStatus("error", "还没有可复制的矢量结果");
return;
}
const label = button.textContent;
button.disabled = true;
try {
const how = await writeSvgToClipboard(currentSvg);
if (!how) throw new Error("当前环境不允许写剪贴板");
button.textContent = "已复制";
const shape = params.splitIslands ? ",粘过去是 " + lastElements + " 个独立元素" : ",粘过去是 1 个整体" + (lastIslands > 1 ? "(" + lastIslands + " 个孤岛已合并)" : "");
setStatus("busy", how === "svg" ? "已复制矢量" + shape + ",直接粘到 Figma / Illustrator 即可" : "已复制 SVG 源码" + shape + "(粘不进去的话改用「下载 SVG」再拖入)");
const text = els ? els.statusText.textContent : "";
window.setTimeout(function() {
if (els && els.statusText.textContent === text) setStatus(null);
}, 2600);
} catch (error) {
setStatus("error", "复制失败:" + (error && error.message ? error.message : String(error)));
} finally {
window.setTimeout(function() {
if (els) {
button.disabled = false;
button.textContent = label;
}
}, 1200);
}
}
function downloadSvg() {
if (!currentSvg) {
setStatus("error", "还没有可下载的矢量结果");
return;
}
const blob = new Blob([currentSvg], { type: "image/svg+xml;charset=utf-8" });
const url = URL.createObjectURL(blob);
const a = document.createElement("a");
a.href = url;
a.download = source.base + "-vector.svg";
document.body.appendChild(a);
a.click();
a.remove();
window.setTimeout(function() {
URL.revokeObjectURL(url);
}, 4e3);
}
async function saveNode(button) {
if (!currentSvg) {
setStatus("error", "还没有可保存的矢量结果");
return;
}
button.disabled = true;
const label = button.textContent;
button.textContent = "生成中…";
try {
const prepared = prepareSource(source.img);
const blob = await svgToPngBlob(currentSvg, prepared.srcW, prepared.srcH, outScale);
await onSaveNode(blob, source.base + ".png");
close();
} catch (error) {
setStatus("error", error && error.message ? error.message : String(error));
button.disabled = false;
button.textContent = label;
}
}
function onPanelInput(event) {
const check = event.target.closest("[data-check]");
if (check && els.panel.contains(check)) {
params[check.dataset.check] = check.checked;
writeSettings();
retrace();
return;
}
const swatch = event.target.closest("[data-color]");
if (swatch && els.panel.contains(swatch)) {
if (!/^#[0-9a-f]{6}$/i.test(swatch.value)) return;
if (swatch.dataset.color === "bg") {
params.bg = swatch.value;
applyPreviewBg();
writeSettings();
if (params.bgExport) scheduleRetrace();
return;
}
params.color = swatch.value;
preset = "";
scheduleRetrace();
return;
}
const input = event.target.closest("[data-param]");
if (!input || !els.panel.contains(input)) return;
const key = input.dataset.param;
const raw = Number(input.value);
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 = input.value;
preset = "";
scheduleRetrace();
}
function onPanelClick(event) {
const adv = event.target.closest('[data-act="adv"]');
if (adv) {
const box = els.panel.querySelector("[data-adv]");
if (box) {
const open2 = box.hidden;
box.hidden = !open2;
advOpen = open2;
adv.setAttribute("aria-expanded", String(open2));
const caret = adv.querySelector("[data-adv-caret]");
if (caret) caret.textContent = open2 ? "▴" : "▾";
writeSettings();
}
return;
}
const presetBtn = event.target.closest("[data-preset]");
if (presetBtn) {
const key = presetBtn.dataset.preset;
if (!PRESETS[key]) return;
preset = key;
params = normalizeParams(Object.assign({}, params, PRESETS[key]));
syncControls();
writeSettings();
retrace();
return;
}
const seg = event.target.closest("[data-seg]");
if (!seg) return;
const name = seg.dataset.seg;
const value = seg.dataset.value;
if (name === "mode") {
params.mode = value === "mono" ? "mono" : "gray";
preset = "";
} else if (name === "levels") {
params.levels = Math.max(LEVELS_MIN, Math.min(LEVELS_MAX, Number(value) || 3));
preset = "";
} else if (name === "alphaTone") {
params.alphaMax = ALPHA_TONE[value] === void 0 ? 1 : ALPHA_TONE[value];
preset = "";
} else if (name === "precision") {
params.optTolerance = TOLERANCE_TONES[value] === void 0 ? DEFAULTS.optTolerance : TOLERANCE_TONES[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 = Math.max(1, Math.min(4, Number(value) || 1));
writeSettings();
syncControls();
return;
} else {
return;
}
syncControls();
scheduleRetrace();
}
function onRootClick(event) {
const act = event.target.closest("[data-act]");
if (!act) return;
const name = act.dataset.act;
if (name === "cancel") {
close();
return;
}
if (name === "copy") {
copySvg(act);
return;
}
if (name === "svg") {
downloadSvg();
return;
}
if (name === "save") {
saveNode(act);
return;
}
}
function onKeyDown(event) {
if (!root) return;
if (event.key === "Escape") {
event.preventDefault();
event.stopPropagation();
close();
return;
}
const keyTag = event.target && event.target.tagName || "";
if (keyTag !== "INPUT" && keyTag !== "TEXTAREA" && keyTag !== "SELECT") {
if (event.key === "0") {
event.preventDefault();
resetView();
return;
}
if (event.key === "+" || event.key === "=") {
event.preventDefault();
zoomAtCenter(1.25);
return;
}
if (event.key === "-" || event.key === "_") {
event.preventDefault();
zoomAtCenter(0.8);
return;
}
}
if (event.code === "Space" && !spaceDown && !event.repeat) {
const tag = event.target && event.target.tagName || "";
if (tag === "INPUT" || tag === "TEXTAREA") return;
event.preventDefault();
spaceDown = true;
updateBadge();
}
}
function onKeyUp(event) {
if (event.code === "Space" && spaceDown) {
spaceDown = false;
updateBadge();
}
}
function onBlur() {
if (spaceDown) {
spaceDown = false;
updateBadge();
}
}
function close() {
if (!root) return;
seq++;
window.clearTimeout(debounceTimer);
document.removeEventListener("keydown", onKeyDown, true);
document.removeEventListener("keyup", onKeyUp, true);
window.removeEventListener("blur", onBlur);
releasePreview();
const node = root;
root = null;
els = null;
zoom = 1;
panX = 0;
panY = 0;
drag = null;
node.remove();
if (typeof onClose === "function") onClose();
}
async function open(request) {
if (root) close();
const stored = readSettings();
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)));
advOpen = stored.advOpen === void 0 ? true : Boolean(stored.advOpen);
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 };
root = document.createElement("div");
root.innerHTML = viewHTML(name);
document.body.appendChild(root);
els = {
root,
modal: root.querySelector(".vz-modal"),
preview: root.querySelector(".vz-preview"),
panel: root.querySelector("[data-panel]"),
vector: root.querySelector('[data-stage="vector"]'),
original: root.querySelector('[data-stage="original"]'),
badge: root.querySelector("[data-badge]"),
zoomChip: root.querySelector("[data-zoom-chip]"),
zoomVal: root.querySelector("[data-zoom-val]"),
status: root.querySelector("[data-status]"),
statusText: root.querySelector("[data-status-text]"),
meta: root.querySelector("[data-meta]")
};
els.original.src = request.imageDataUrl;
els.meta.textContent = name + " · " + source.srcW + "×" + source.srcH;
els.panel.innerHTML = panelHTML(params, preset, outScale, advOpen);
root.addEventListener("click", onRootClick);
els.preview.addEventListener("wheel", onPreviewWheel, { passive: false });
els.preview.addEventListener("pointerdown", onPreviewPointerDown);
els.preview.addEventListener("pointermove", onPreviewPointerMove);
els.preview.addEventListener("pointerup", onPreviewPointerUp);
els.preview.addEventListener("pointercancel", onPreviewPointerUp);
els.preview.addEventListener("lostpointercapture", onPreviewPointerUp);
els.preview.addEventListener("dblclick", onPreviewDblClick);
els.preview.addEventListener("click", function(event) {
if (event.target.closest(".vz-zoom")) resetView();
});
els.panel.addEventListener("input", onPanelInput);
els.panel.addEventListener("click", onPanelClick);
document.addEventListener("keydown", onKeyDown, true);
document.addEventListener("keyup", onKeyUp, true);
window.addEventListener("blur", onBlur);
syncControls();
setStats(null);
resetView();
retrace();
return { close };
}
return { open, close };
}
// image-vectorize/plugin/entry.js
(typeof window !== "undefined" ? window : globalThis).__IWB_VECTORIZE_FACTORY__ = function(ctx) {
let styleInjected = false;
function ensureStyle() {
if (styleInjected) return;
try {
const style = document.createElement("style");
style.id = "iwb-vectorize-style";
style.textContent = ui_default;
(document.head || document.documentElement).appendChild(style);
styleInjected = true;
} catch (error) {
ctx.log("vectorize-style-failed", error && error.message);
}
}
function blobToDataUrl(blob) {
return new Promise(function(resolve, reject) {
const reader = new FileReader();
reader.onload = function() {
resolve(String(reader.result || ""));
};
reader.onerror = function() {
reject(reader.error || new Error("读取图片失败"));
};
reader.readAsDataURL(blob);
});
}
async function resolveImage(nodeId) {
const image = await ctx.canvas.getNodeImage(nodeId);
if (!image) throw new Error("该节点没有可描摹的图片");
if (image.dataUrl) return image.dataUrl;
if (!image.url) throw new Error("该节点没有可描摹的图片");
let resp;
try {
resp = await fetch(image.url);
} catch (error) {
throw new Error("远程图片无法读取(可能被跨域限制):请先转存为本地位图");
}
if (!resp.ok) throw new Error("远程图片无法读取(可能被跨域限制):请先转存为本地位图");
const blob = await resp.blob();
const objectUrl = URL.createObjectURL(blob);
try {
await loadImage(objectUrl);
} finally {
URL.revokeObjectURL(objectUrl);
}
return blobToDataUrl(blob);
}
let active = null;
async function runOne(node) {
if (!node || !node.id) throw new Error("请先选中一个带图的节点");
ensureStyle();
const imageDataUrl = await resolveImage(node.id);
if (active) {
try {
active.close();
} catch (e) {
}
}
return new Promise(function(resolve, reject) {
let settled = false;
const settle = function(fn) {
if (!settled) {
settled = true;
fn();
}
};
active = createVectorizer({
settings: ctx.settings,
onSaveNode: async function(blob, name) {
const dataUrl = await blobToDataUrl(blob);
const created = ctx.canvas.createImageNode({ dataUrl, name });
if (!created) throw new Error("写回画布失败");
ctx.log("vectorize: " + name + " " + Math.round(blob.size / 1024) + "KB");
settle(function() {
resolve(name);
});
},
onClose: function() {
active = null;
settle(function() {
resolve("cancel");
});
},
onError: function(message) {
settle(function() {
reject(new Error(String(message || "描摹失败")));
});
}
});
Promise.resolve(active.open({ imageDataUrl, name: node.name })).catch(function(error) {
active = null;
settle(function() {
reject(error);
});
});
});
}
ctx.nodeActions.register({
id: "vectorize-node",
title: "位图转矢量",
icon: "pen-tool",
appliesTo: function(node) {
return Boolean(node) && node.type === "ref";
},
run: function(node) {
return runOne(node);
}
});
ctx.commands.register({
id: "vectorize-selected",
title: "位图转矢量:选中节点",
icon: "pen-tool",
run: function() {
const selected = ctx.canvas.getSelectedNode();
if (!selected) return Promise.reject(new Error("请先选中一个带图的节点"));
return runOne(selected);
}
});
return {};
};
})();
// 手写注册尾部(build-plugin.mjs 原样追加到产物末尾,不 overlapped with esbuild 的打印器)。
// 时序:bundle 先执行(挂好 __IWB_VECTORIZE_FACTORY__),再注册;factory 由宿主在「启用插件」时才调用。
;(function (global) {
'use strict'
if (!global.IWBPluginHost) return
global.IWBPluginHost.register(__IWB_VECTORIZE_MANIFEST__, function (ctx) {
return global.__IWB_VECTORIZE_FACTORY__(ctx)
})
})(typeof window !== 'undefined' ? window : globalThis)