Files
iwb-plugins-desktop/image-vectorize/src/index.js
T
qiqi c4e4b15375 feat(image-vectorize): v0.2 换 potrace 引擎,只做单色/灰度
用户裁定「只要单色/灰度就够」后重做:VTracer(彩色分层 wasm)换成 potrace
(纯 JS,Inkscape 同款内核)。文字笔画完整、turdSize 去掉毛刺、灰度层数 2–5。

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

2771 lines
117 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 替换,保证两处永不漂移。
var __IWB_VECTORIZE_MANIFEST__ = {
id: 'image-vectorize',
name: '位图转矢量',
version: '0.2.0',
apiVersion: 1,
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 },
invert: { type: 'boolean', default: false },
color: { type: 'string', default: '#1a1a1a' },
outScale: { type: 'number', default: 2 }
},
}
"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 = '/* 位图转矢量:全屏模态。深色,与「标注 / 修图」同一套视觉语言。\n CSP:由宿主 style-src \'unsafe-inline\' 放行,运行时注入 <style>。 */\n\n.vz-root {\n position: fixed;\n inset: 0;\n z-index: 2147483000;\n display: flex;\n align-items: center;\n justify-content: center;\n background: rgba(10, 10, 14, 0.72);\n font: 13px/1.5 -apple-system, BlinkMacSystemFont, "PingFang SC", "Microsoft YaHei", sans-serif;\n color: #e6e6ef;\n}\n\n.vz-modal {\n display: flex;\n flex-direction: column;\n width: 92vw;\n height: 88vh;\n min-width: 760px;\n min-height: 520px;\n max-width: 1680px;\n background: #1b1b22;\n border: 1px solid #33333f;\n border-radius: 12px;\n box-shadow: 0 24px 64px rgba(0, 0, 0, 0.55);\n overflow: hidden;\n}\n\n/* ---------- 顶栏 ---------- */\n.vz-header {\n display: flex;\n align-items: center;\n gap: 10px;\n flex: 0 0 auto;\n height: 52px;\n padding: 0 14px;\n background: #202029;\n border-bottom: 1px solid #2e2e3a;\n}\n\n.vz-title {\n font-size: 13px;\n font-weight: 500;\n color: #f0f0f7;\n white-space: nowrap;\n}\n\n.vz-title em {\n font-style: normal;\n color: #8b8b9e;\n font-weight: 400;\n margin-left: 8px;\n}\n\n.vz-title em b {\n color: #d6d6e4;\n font-weight: 500;\n}\n\n.vz-spacer { flex: 1 1 auto; }\n\n.vz-btn {\n height: 32px;\n padding: 0 14px;\n border: 1px solid #3c3c4c;\n border-radius: 7px;\n background: #2a2a35;\n color: #d8d8e4;\n font-size: 12px;\n cursor: pointer;\n white-space: nowrap;\n}\n.vz-btn:hover { background: #34343f; border-color: #4a4a5c; }\n.vz-btn:active { background: #2f2f3a; }\n.vz-btn:disabled { opacity: 0.45; cursor: default; }\n\n.vz-btn-primary {\n background: #1f7a52;\n border-color: #27875c;\n color: #eafff5;\n}\n.vz-btn-primary:hover { background: #248a5d; border-color: #2f9c69; }\n.vz-btn-primary:disabled { background: #24503e; border-color: #2a5c47; }\n\n/* ---------- 主体 ---------- */\n.vz-body {\n display: flex;\n flex: 1 1 auto;\n min-height: 0;\n}\n\n.vz-preview {\n position: relative;\n flex: 1 1 auto;\n min-width: 0;\n display: flex;\n align-items: center;\n justify-content: center;\n padding: 20px;\n overflow: hidden;\n /* 透明区用中性灰棋盘,不用深色:电商素材里大量是黑字/深色 logo,\n 深色棋盘会把这些内容直接吞掉,看起来像「描摹失败」 */\n background-color: #c8c8c8;\n background-image:\n linear-gradient(45deg, #a8a8a8 25%, transparent 25%, transparent 75%, #a8a8a8 75%),\n linear-gradient(45deg, #a8a8a8 25%, transparent 25%, transparent 75%, #a8a8a8 75%);\n background-size: 20px 20px;\n background-position: 0 0, 10px 10px;\n}\n\n.vz-stage {\n max-width: 100%;\n max-height: 100%;\n display: block;\n box-shadow: 0 4px 24px rgba(0, 0, 0, 0.35);\n}\n\n.vz-stage[hidden] { display: none; }\n\n.vz-badge {\n position: absolute;\n top: 14px;\n left: 14px;\n padding: 4px 9px;\n border-radius: 6px;\n background: rgba(18, 18, 24, 0.82);\n border: 1px solid #33333f;\n color: #a8a8bb;\n font-size: 11px;\n letter-spacing: 0.2px;\n}\n\n.vz-hint {\n position: absolute;\n bottom: 14px;\n left: 50%;\n transform: translateX(-50%);\n color: #75758a;\n font-size: 11px;\n pointer-events: none;\n white-space: nowrap;\n}\n\n/* 描摹中/出错的浮层 */\n.vz-status {\n position: absolute;\n top: 14px;\n right: 14px;\n display: flex;\n align-items: center;\n gap: 8px;\n padding: 5px 11px;\n border-radius: 7px;\n font-size: 11px;\n background: rgba(18, 18, 24, 0.88);\n border: 1px solid #33333f;\n color: #b9b9cc;\n}\n.vz-status[hidden] { display: none; }\n.vz-status.is-busy { color: #ffd08a; border-color: #5a4526; }\n.vz-status.is-error { color: #ff9c9c; border-color: #5c2c2c; max-width: 60%; }\n\n.vz-dot {\n width: 7px;\n height: 7px;\n border-radius: 50%;\n background: currentColor;\n flex: 0 0 auto;\n}\n.vz-status.is-busy .vz-dot { animation: vz-pulse 1s ease-in-out infinite; }\n@keyframes vz-pulse { 0%, 100% { opacity: 0.25; } 50% { opacity: 1; } }\n\n/* ---------- 参数面板 ---------- */\n.vz-panel {\n flex: 0 0 auto;\n width: 312px;\n padding: 14px 16px 18px;\n background: #1e1e26;\n border-left: 1px solid #2e2e3a;\n overflow-y: auto;\n}\n\n.vz-panel::-webkit-scrollbar { width: 8px; }\n.vz-panel::-webkit-scrollbar-thumb { background: #3a3a48; border-radius: 4px; }\n\n.vz-group + .vz-group { margin-top: 18px; padding-top: 16px; border-top: 1px solid #2b2b36; }\n\n.vz-group-title {\n font-size: 11px;\n color: #7e7e94;\n letter-spacing: 0.6px;\n margin-bottom: 9px;\n text-transform: none;\n}\n\n/* 预设 */\n.vz-presets {\n display: grid;\n grid-template-columns: 1fr 1fr;\n gap: 7px;\n}\n\n.vz-preset {\n display: flex;\n flex-direction: column;\n gap: 2px;\n padding: 8px 9px;\n border: 1px solid #37374a;\n border-radius: 8px;\n background: #262631;\n color: #d5d5e2;\n font-size: 12px;\n text-align: left;\n cursor: pointer;\n}\n.vz-preset small {\n color: #7b7b91;\n font-size: 10px;\n line-height: 1.35;\n}\n.vz-preset:hover { background: #2e2e3b; border-color: #45455a; }\n.vz-preset.active {\n background: #1f3a30;\n border-color: #2f7d5b;\n color: #d8ffe9;\n}\n.vz-preset.active small { color: #79b79b; }\n\n/* 分段控件 */\n.vz-row { margin-bottom: 11px; }\n/* 按模式隐藏的行(层数只在灰度、阈值只在手动)必须真的消失。\n 踩过的坑:flex/块级元素上加 `hidden` 属性,如果 CSS 里另有 display 声明就会失效,\n 于是「隐藏」只变成视觉上还在 —— 这里直接 !important 兜住所有形态。 */\n.vz-row[hidden] { display: none !important; }\n.vz-row:last-child { margin-bottom: 0; }\n\n.vz-row-label {\n display: flex;\n align-items: center;\n justify-content: space-between;\n font-size: 12px;\n color: #b6b6c8;\n margin-bottom: 6px;\n}\n\n.vz-row-label span { color: #6f6f85; font-size: 11px; }\n\n.vz-seg {\n display: flex;\n gap: 0;\n border: 1px solid #3a3a4a;\n border-radius: 7px;\n overflow: hidden;\n}\n\n.vz-seg button {\n flex: 1 1 0;\n height: 28px;\n border: 0;\n border-right: 1px solid #3a3a4a;\n background: #24242e;\n color: #a8a8bd;\n font-size: 11.5px;\n cursor: pointer;\n white-space: nowrap;\n}\n.vz-seg button:last-child { border-right: 0; }\n.vz-seg button:hover { background: #2c2c38; color: #d0d0e0; }\n.vz-seg button.active { background: #33566f; color: #eaf6ff; }\n\n/* 滑杆 */\n.vz-range {\n display: flex;\n align-items: center;\n gap: 9px;\n}\n\n.vz-range input[type="range"] {\n flex: 1 1 auto;\n min-width: 0;\n height: 4px;\n -webkit-appearance: none;\n appearance: none;\n background: #3a3a4a;\n border-radius: 2px;\n outline: none;\n}\n.vz-range input[type="range"]::-webkit-slider-thumb {\n -webkit-appearance: none;\n appearance: none;\n width: 13px;\n height: 13px;\n border-radius: 50%;\n background: #cfcfdd;\n border: 0;\n cursor: pointer;\n}\n.vz-range input[type="range"]:disabled { opacity: 0.4; }\n.vz-range input[type="range"]:disabled::-webkit-slider-thumb { cursor: default; }\n\n.vz-range-val {\n flex: 0 0 auto;\n min-width: 34px;\n text-align: right;\n font-size: 11.5px;\n color: #d0d0e0;\n font-variant-numeric: tabular-nums;\n}\n\n/* 高级参数折叠:首屏只露高频项,低频参数收起来但一档可达 */\n.vz-adv-toggle {\n display: flex;\n align-items: center;\n justify-content: space-between;\n width: 100%;\n height: 30px;\n padding: 0 10px;\n border: 1px solid #37374a;\n border-radius: 7px;\n background: #24242e;\n color: #a8a8bd;\n font-size: 11.5px;\n cursor: pointer;\n}\n.vz-adv-toggle:hover { background: #2c2c38; color: #d0d0e0; }\n.vz-adv-toggle span { color: #6f6f85; }\n\n/* 单色填充色(仅「纯单色」生效)。原生 color input 在深色面板里默认边框很亮,\n 去掉内边距与外框,只留一块颜色本身,和滑杆行视觉一致 */\n.vz-color {\n flex: 0 0 auto;\n width: 42px;\n height: 22px;\n padding: 0;\n border: 1px solid #45455a;\n border-radius: 6px;\n background: transparent;\n cursor: pointer;\n}\n.vz-color::-webkit-color-swatch-wrapper { padding: 2px; }\n.vz-color::-webkit-color-swatch { border: none; border-radius: 4px; }\n.vz-color:disabled { cursor: default; }\n\n\n.vz-adv { margin-top: 10px; }\n.vz-adv[hidden] { display: none; }\n\n/* 统计 */\n.vz-stats {\n display: flex;\n gap: 14px;\n flex-wrap: wrap;\n font-size: 11.5px;\n color: #8f8fa4;\n}\n.vz-stats b { color: #d8d8e6; font-weight: 500; }\n\n.vz-note {\n margin-top: 9px;\n font-size: 10.5px;\n line-height: 1.55;\n color: #6b6b80;\n}\n\n/* 窄屏:面板转到底部 */\n@media (max-width: 900px) {\n .vz-modal { width: 96vw; height: 92vh; min-width: 0; }\n .vz-body { flex-direction: column; }\n .vz-panel { width: auto; max-height: 46%; border-left: 0; border-top: 1px solid #2e2e3a; }\n}\n';
// image-vectorize/plugin/engine.js
var import_Potrace = __toESM(require_Potrace());
var import_Posterizer = __toESM(require_Posterizer());
var LEVELS_MIN = 2;
var LEVELS_MAX = 5;
var MAX_TRACE_SIDE = 2e3;
var DEFAULTS = {
mode: "gray",
// 'gray' 灰度分层 / 'mono' 纯单色
levels: 3,
// 灰度层数(2–5,仅 gray)
threshold: -1,
// -1 = 自动(两种模式都支持)
turdSize: 3,
// 去小点:面积小于它的碎片直接丢(毛刺/噪点克星)
alphaMax: 1,
// 拐角平滑:0 全折线、1 默认、1.334 最圆
invert: false,
// 反相:描摹亮部(黑底白字场景)
color: "#1a1a1a",
// mono 的填充色
outScale: 1
// 输出尺寸倍率(只放大尺寸,不重算曲线)
};
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;
})(),
invert: Boolean(src.invert),
color: /^#[0-9a-f]{6}$/i.test(String(src.color || "")) ? String(src.color) : DEFAULTS.color,
outScale: Math.min(4, Math.max(1, Number(src.outScale) || 1))
};
}
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: 0.2,
blackOnWhite: !p.invert,
color: p.color
});
potrace.loadImageData(imageData);
svg = potrace.getSVG();
} else {
const cuts = quantileThresholds(imageData, p.levels);
levels = cuts.length + 1;
const posterizer = new 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: 0.2,
blackOnWhite: !p.invert,
fillStrategy: "median",
// 灰度:每层取该层亮度中位数
color: "#000000"
// 灰度靠 fill-opacity 叠出来,底色固定黑
});
posterizer.loadImageData(imageData);
svg = posterizer.getSVG();
}
return { svg, ms: Math.round(now() - t0), paths: (String(svg).match(/<path/g) || []).length, 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", "invert", "color", "outScale"];
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) {
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">边缘</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><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><div class="vz-group"><div class="vz-stats"><span><b data-stat="paths">–</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="false">高级参数<span data-adv-caret>▾</span></button><div class="vz-adv" data-adv 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><input type="color" class="vz-color" data-color="color" value="' + esc(params.color) + '"></div><div class="vz-note">矢量结果可无限放大不失真。「保存为节点」输出 PNG(按输出倍率重绘),要真矢量文件用「下载 SVG」。</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="cancel">取消</button><button type="button" class="vz-btn" data-act="svg">下载 SVG</button><button type="button" class="vz-btn vz-btn-primary" data-act="save">保存为节点</button></header><div class="vz-body"><div class="vz-preview"><img class="vz-stage" data-stage="vector" alt="矢量预览"><img class="vz-stage" data-stage="original" alt="原图" 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><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";
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 currentSvg = "";
let currentBlobUrl = "";
let seq = 0;
let debounceTimer = 0;
let spaceDown = false;
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") value = value === true || value === "true" || value === 1 || value === "1";
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("invert", params.invert);
settings.set("color", params.color);
settings.set("outScale", outScale);
} 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("paths", "–");
put("levels", "–");
put("bytes", "–");
put("ms", "–");
return;
}
put("paths", String(stats.paths));
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="invert"] button').forEach(function(btn) {
btn.classList.toggle("active", btn.dataset.value === "1" === params.invert);
});
panel.querySelectorAll('[data-seg-group="thrMode"] button').forEach(function(btn) {
btn.classList.toggle("active", btn.dataset.value === "manual" === params.threshold >= 0);
});
panel.querySelectorAll('[data-seg-group="outScale"] button').forEach(function(btn) {
btn.classList.toggle("active", Number(btn.dataset.value) === outScale);
});
const thrRow = panel.querySelector("[data-thr-row]");
if (thrRow) thrRow.hidden = params.threshold < 0;
const colorInput = panel.querySelector('[data-color="color"]');
if (colorInput) {
colorInput.value = params.color;
colorInput.disabled = params.mode !== "mono";
colorInput.parentElement.style.opacity = params.mode === "mono" ? "" : "0.45";
}
}
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 ? "原图" : "矢量预览";
}
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);
setStats(svgStats(currentSvg), out.ms, out.levels);
setStatus(null);
if (prepared.clamped) {
setStatus("busy", "大图已降到 " + prepared.w + "×" + prepared.h + " 再描摹");
window.setTimeout(function() {
if (ticket === seq) setStatus(null);
}, 2600);
}
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);
}
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 color = event.target.closest("[data-color]");
if (color && els.panel.contains(color)) {
if (!/^#[0-9a-f]{6}$/i.test(color.value)) return;
params.color = color.value;
preset = "";
scheduleRetrace();
return;
}
const input = event.target.closest("[data-param]");
if (!input || !els.panel.contains(input)) return;
const key = input.dataset.param;
const 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;
adv.setAttribute("aria-expanded", String(open2));
const caret = adv.querySelector("[data-adv-caret]");
if (caret) caret.textContent = open2 ? "▴" : "▾";
}
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 === "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 === "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;
}
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;
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)));
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"),
panel: root.querySelector("[data-panel]"),
vector: root.querySelector('[data-stage="vector"]'),
original: root.querySelector('[data-stage="original"]'),
badge: root.querySelector("[data-badge]"),
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);
root.addEventListener("click", onRootClick);
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);
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)