magic-img
Version:
1,236 lines (1,235 loc) • 45.7 kB
JavaScript
function _arrayLikeToArray(arr, len) {
if (len == null || len > arr.length) len = arr.length;
for(var i = 0, arr2 = new Array(len); i < len; i++)arr2[i] = arr[i];
return arr2;
}
function _arrayWithHoles(arr) {
if (Array.isArray(arr)) return arr;
}
function _arrayWithoutHoles(arr) {
if (Array.isArray(arr)) return _arrayLikeToArray(arr);
}
function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) {
try {
var info = gen[key](arg);
var value = info.value;
} catch (error) {
reject(error);
return;
}
if (info.done) {
resolve(value);
} else {
Promise.resolve(value).then(_next, _throw);
}
}
function _asyncToGenerator(fn) {
return function() {
var self = this, args = arguments;
return new Promise(function(resolve, reject) {
var gen = fn.apply(self, args);
function _next(value) {
asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value);
}
function _throw(err) {
asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err);
}
_next(undefined);
});
};
}
function _defineProperty(obj, key, value) {
if (key in obj) {
Object.defineProperty(obj, key, {
value: value,
enumerable: true,
configurable: true,
writable: true
});
} else {
obj[key] = value;
}
return obj;
}
function _iterableToArray(iter) {
if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter);
}
function _iterableToArrayLimit(arr, i) {
var _i = arr == null ? null : typeof Symbol !== "undefined" && arr[Symbol.iterator] || arr["@@iterator"];
if (_i == null) return;
var _arr = [];
var _n = true;
var _d = false;
var _s, _e;
try {
for(_i = _i.call(arr); !(_n = (_s = _i.next()).done); _n = true){
_arr.push(_s.value);
if (i && _arr.length === i) break;
}
} catch (err) {
_d = true;
_e = err;
} finally{
try {
if (!_n && _i["return"] != null) _i["return"]();
} finally{
if (_d) throw _e;
}
}
return _arr;
}
function _nonIterableRest() {
throw new TypeError("Invalid attempt to destructure non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
}
function _nonIterableSpread() {
throw new TypeError("Invalid attempt to spread non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
}
function _objectSpread(target) {
for(var i = 1; i < arguments.length; i++){
var source = arguments[i] != null ? arguments[i] : {};
var ownKeys = Object.keys(source);
if (typeof Object.getOwnPropertySymbols === "function") {
ownKeys = ownKeys.concat(Object.getOwnPropertySymbols(source).filter(function(sym) {
return Object.getOwnPropertyDescriptor(source, sym).enumerable;
}));
}
ownKeys.forEach(function(key) {
_defineProperty(target, key, source[key]);
});
}
return target;
}
function _objectWithoutProperties(source, excluded) {
if (source == null) return {};
var target = _objectWithoutPropertiesLoose(source, excluded);
var key, i;
if (Object.getOwnPropertySymbols) {
var sourceSymbolKeys = Object.getOwnPropertySymbols(source);
for(i = 0; i < sourceSymbolKeys.length; i++){
key = sourceSymbolKeys[i];
if (excluded.indexOf(key) >= 0) continue;
if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue;
target[key] = source[key];
}
}
return target;
}
function _objectWithoutPropertiesLoose(source, excluded) {
if (source == null) return {};
var target = {};
var sourceKeys = Object.keys(source);
var key, i;
for(i = 0; i < sourceKeys.length; i++){
key = sourceKeys[i];
if (excluded.indexOf(key) >= 0) continue;
target[key] = source[key];
}
return target;
}
function _slicedToArray(arr, i) {
return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest();
}
function _toConsumableArray(arr) {
return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _nonIterableSpread();
}
function _unsupportedIterableToArray(o, minLen) {
if (!o) return;
if (typeof o === "string") return _arrayLikeToArray(o, minLen);
var n = Object.prototype.toString.call(o).slice(8, -1);
if (n === "Object" && o.constructor) n = o.constructor.name;
if (n === "Map" || n === "Set") return Array.from(n);
if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen);
}
var __generator = this && this.__generator || function(thisArg, body) {
var f, y, t, g, _ = {
label: 0,
sent: function() {
if (t[0] & 1) throw t[1];
return t[1];
},
trys: [],
ops: []
};
return g = {
next: verb(0),
"throw": verb(1),
"return": verb(2)
}, typeof Symbol === "function" && (g[Symbol.iterator] = function() {
return this;
}), g;
function verb(n) {
return function(v) {
return step([
n,
v
]);
};
}
function step(op) {
if (f) throw new TypeError("Generator is already executing.");
while(_)try {
if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
if (y = 0, t) op = [
op[0] & 2,
t.value
];
switch(op[0]){
case 0:
case 1:
t = op;
break;
case 4:
_.label++;
return {
value: op[1],
done: false
};
case 5:
_.label++;
y = op[1];
op = [
0
];
continue;
case 7:
op = _.ops.pop();
_.trys.pop();
continue;
default:
if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) {
_ = 0;
continue;
}
if (op[0] === 3 && (!t || op[1] > t[0] && op[1] < t[3])) {
_.label = op[1];
break;
}
if (op[0] === 6 && _.label < t[1]) {
_.label = t[1];
t = op;
break;
}
if (t && _.label < t[2]) {
_.label = t[2];
_.ops.push(op);
break;
}
if (t[2]) _.ops.pop();
_.trys.pop();
continue;
}
op = body.call(thisArg, _);
} catch (e) {
op = [
6,
e
];
y = 0;
} finally{
f = t = 0;
}
if (op[0] & 5) throw op[1];
return {
value: op[0] ? op[1] : void 0,
done: true
};
}
};
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 __export = function(target, all) {
for(var name in all)__defProp(target, name, {
get: all[name],
enumerable: true
});
};
var __copyProps = function(to, from, except, desc) {
if (from && typeof from === "object" || typeof from === "function") {
var _iteratorNormalCompletion = true, _didIteratorError = false, _iteratorError = undefined;
try {
var _loop = function() {
var key = _step.value;
if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, {
get: function() {
return from[key];
},
enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable
});
};
for(var _iterator = __getOwnPropNames(from)[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true)_loop();
} catch (err) {
_didIteratorError = true;
_iteratorError = err;
} finally{
try {
if (!_iteratorNormalCompletion && _iterator.return != null) {
_iterator.return();
}
} finally{
if (_didIteratorError) {
throw _iteratorError;
}
}
}
}
return to;
};
var __toESM = function(mod, isNodeMode, target) {
return target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", {
value: mod,
enumerable: true
}) : target, mod);
};
var __toCommonJS = function(mod) {
return __copyProps(__defProp({}, "__esModule", {
value: true
}), mod);
};
// src/vite.ts
var vite_exports = {};
__export(vite_exports, {
default: function() {
return vite_default;
}
});
module.exports = __toCommonJS(vite_exports);
// src/core/draw/canny.ts
var CannyJS;
var GrayImageData;
var Util;
Util = {};
Util.generateMatrix = function(w, h, initialValue) {
var matrix, x, y, _i, _j, _ref, _ref1;
matrix = [];
for(x = _i = 0, _ref = w - 1; 0 <= _ref ? _i <= _ref : _i >= _ref; x = 0 <= _ref ? ++_i : --_i){
matrix[x] = [];
for(y = _j = 0, _ref1 = h - 1; 0 <= _ref1 ? _j <= _ref1 : _j >= _ref1; y = 0 <= _ref1 ? ++_j : --_j){
matrix[x][y] = initialValue;
}
}
return matrix;
};
GrayImageData = function() {
var GrayImageData2 = function GrayImageData2(width, height) {
this.width = width;
this.height = height;
this.data = Util.generateMatrix(this.width, this.height, 0);
this;
};
GrayImageData2.prototype.loadCanvas = function(rawdata) {
var b, ctx, d, g, i, r, x, y, _i, _len;
x = 0;
y = 0;
for(i = _i = 0, _len = rawdata.length; _i < _len; i = _i += 4){
d = rawdata[i];
r = rawdata[i];
g = rawdata[i + 1];
b = rawdata[i + 2];
this.data[x][y] = Math.round(0.298 * r + 0.586 * g + 0.114 * b);
if (x === this.width - 1) {
x = 0;
y += 1;
} else {
x += 1;
}
}
return this;
};
GrayImageData2.prototype.getNeighbors = function(x, y, size) {
var i, j, neighbors, trnsX, trnsY, _i, _j, _ref, _ref1;
neighbors = Util.generateMatrix(size, size, 0);
for(i = _i = 0, _ref = size - 1; 0 <= _ref ? _i <= _ref : _i >= _ref; i = 0 <= _ref ? ++_i : --_i){
neighbors[i] = [];
for(j = _j = 0, _ref1 = size - 1; 0 <= _ref1 ? _j <= _ref1 : _j >= _ref1; j = 0 <= _ref1 ? ++_j : --_j){
trnsX = x - (size - 1) / 2 + i;
trnsY = y - (size - 1) / 2 + j;
if (this.data[trnsX] && this.data[trnsX][trnsY]) {
neighbors[i][j] = this.data[trnsX][trnsY];
} else {
neighbors[i][j] = 0;
}
}
}
return neighbors;
};
GrayImageData2.prototype.eachPixel = function(neighborSize, func) {
var current, neighbors, x, y, _i, _j, _ref, _ref1;
for(x = _i = 0, _ref = this.width - 1; 0 <= _ref ? _i <= _ref : _i >= _ref; x = 0 <= _ref ? ++_i : --_i){
for(y = _j = 0, _ref1 = this.height - 1; 0 <= _ref1 ? _j <= _ref1 : _j >= _ref1; y = 0 <= _ref1 ? ++_j : --_j){
current = this.data[x][y];
neighbors = this.getNeighbors(x, y, neighborSize);
func(x, y, current, neighbors);
}
}
return this;
};
GrayImageData2.prototype.toImageDataArray = function() {
var ary, i, x, y, _i, _j, _k, _ref, _ref1;
ary = [];
for(y = _i = 0, _ref = this.height - 1; 0 <= _ref ? _i <= _ref : _i >= _ref; y = 0 <= _ref ? ++_i : --_i){
for(x = _j = 0, _ref1 = this.width - 1; 0 <= _ref1 ? _j <= _ref1 : _j >= _ref1; x = 0 <= _ref1 ? ++_j : --_j){
for(i = _k = 0; _k <= 2; i = ++_k){
ary.push(this.data[x][y]);
}
ary.push(255);
}
}
return ary;
};
GrayImageData2.prototype.copy = function() {
var copied, x, y, _i, _j, _ref, _ref1;
copied = new GrayImageData2(this.width, this.height);
for(x = _i = 0, _ref = this.width - 1; 0 <= _ref ? _i <= _ref : _i >= _ref; x = 0 <= _ref ? ++_i : --_i){
for(y = _j = 0, _ref1 = this.height - 1; 0 <= _ref1 ? _j <= _ref1 : _j >= _ref1; y = 0 <= _ref1 ? ++_j : --_j){
copied.data[x][y] = this.data[x][y];
}
}
copied.width = this.width;
copied.height = this.height;
return copied;
};
GrayImageData2.prototype.drawOn = function(canvas) {
var color, ctx, i, imgData, _i, _len, _ref;
ctx = canvas.getContext("2d");
imgData = ctx.createImageData(canvas.width, canvas.height);
_ref = this.toImageDataArray();
for(i = _i = 0, _len = _ref.length; _i < _len; i = ++_i){
color = _ref[i];
imgData.data[i] = color;
}
return ctx.putImageData(imgData, 0, 0);
};
GrayImageData2.prototype.fill = function(color) {
var x, y, _i, _ref, _results;
_results = [];
for(y = _i = 0, _ref = this.height - 1; 0 <= _ref ? _i <= _ref : _i >= _ref; y = 0 <= _ref ? ++_i : --_i){
_results.push((function() {
var _j, _ref1, _results1;
_results1 = [];
for(x = _j = 0, _ref1 = this.width - 1; 0 <= _ref1 ? _j <= _ref1 : _j >= _ref1; x = 0 <= _ref1 ? ++_j : --_j){
_results1.push(this.data[x][y] = color);
}
return _results1;
}).call(this));
}
return _results;
};
return GrayImageData2;
}();
CannyJS = {};
CannyJS.gaussianBlur = function(imgData, sigmma, size) {
var copy, kernel;
if (sigmma == null) {
sigmma = 1.4;
}
if (size == null) {
size = 3;
}
kernel = CannyJS.generateKernel(sigmma, size);
copy = imgData.copy();
copy.fill(0);
imgData.eachPixel(size, function(x, y, current, neighbors) {
var i, j, _results;
i = 0;
_results = [];
while(i <= size - 1){
j = 0;
while(j <= size - 1){
copy.data[x][y] += neighbors[i][j] * kernel[i][j];
j++;
}
_results.push(i++);
}
return _results;
});
return copy;
};
CannyJS.generateKernel = function(sigmma, size) {
var _$e, gaussian, i, j, kernel, s, sum, x, y, _i, _j, _k, _l, _ref, _ref1, _ref2, _ref3;
s = sigmma;
_$e = 2.718;
kernel = Util.generateMatrix(size, size, 0);
sum = 0;
for(i = _i = 0, _ref = size - 1; 0 <= _ref ? _i <= _ref : _i >= _ref; i = 0 <= _ref ? ++_i : --_i){
x = -(size - 1) / 2 + i;
for(j = _j = 0, _ref1 = size - 1; 0 <= _ref1 ? _j <= _ref1 : _j >= _ref1; j = 0 <= _ref1 ? ++_j : --_j){
y = -(size - 1) / 2 + j;
gaussian = 1 / (2 * Math.PI * s * s) * Math.pow(_$e, -(x * x + y * y) / (2 * s * s));
kernel[i][j] = gaussian;
sum += gaussian;
}
}
for(i = _k = 0, _ref2 = size - 1; 0 <= _ref2 ? _k <= _ref2 : _k >= _ref2; i = 0 <= _ref2 ? ++_k : --_k){
for(j = _l = 0, _ref3 = size - 1; 0 <= _ref3 ? _l <= _ref3 : _l >= _ref3; j = 0 <= _ref3 ? ++_l : --_l){
kernel[i][j] = (kernel[i][j] / sum).toFixed(3);
}
}
return kernel;
};
CannyJS.sobel = function(imgData) {
var copy, xFiler, yFiler;
yFiler = [
[
-1,
0,
1
],
[
-2,
0,
2
],
[
-1,
0,
1
]
];
xFiler = [
[
-1,
-2,
-1
],
[
0,
0,
0
],
[
1,
2,
1
]
];
copy = imgData.copy();
copy.fill(0);
imgData.eachPixel(3, function(x, y, current, neighbors) {
var ghs, gvs, i, j, _i, _j;
ghs = 0;
gvs = 0;
for(i = _i = 0; _i <= 2; i = ++_i){
for(j = _j = 0; _j <= 2; j = ++_j){
ghs += yFiler[i][j] * neighbors[i][j];
gvs += xFiler[i][j] * neighbors[i][j];
}
}
return copy.data[x][y] = Math.sqrt(ghs * ghs + gvs * gvs);
});
return copy;
};
CannyJS.nonMaximumSuppression = function(imgData) {
var copy;
copy = imgData.copy();
copy.fill(0);
imgData.eachPixel(3, function(x, y, c, n) {
if (n[1][1] > n[0][1] && n[1][1] > n[2][1]) {
copy.data[x][y] = n[1][1];
} else {
copy.data[x][y] = 0;
}
if (n[1][1] > n[0][2] && n[1][1] > n[2][0]) {
copy.data[x][y] = n[1][1];
} else {
copy.data[x][y] = 0;
}
if (n[1][1] > n[1][0] && n[1][1] > n[1][2]) {
copy.data[x][y] = n[1][1];
} else {
copy.data[x][y] = 0;
}
if (n[1][1] > n[0][0] && n[1][1] > n[2][2]) {
return copy.data[x][y] = n[1][1];
} else {
return copy.data[x][y] = 0;
}
});
return copy;
};
CannyJS.hysteresis = function(imgData, ht, lt) {
var copy, isCandidate, isStrong, isWeak, traverseEdge;
copy = imgData.copy();
isStrong = function isStrong(edge) {
return edge > ht;
};
isCandidate = function isCandidate(edge) {
return edge <= ht && edge >= lt;
};
isWeak = function isWeak(edge) {
return edge < lt;
};
imgData.eachPixel(3, function(x, y, current, neighbors) {
if (isStrong(current)) {
return copy.data[x][y] = 255;
} else if (isWeak(current) || isCandidate(current)) {
return copy.data[x][y] = 0;
}
});
traverseEdge = function(x, y) {
var i, j, neighbors, _i, _results;
if (x === 0 || y === 0 || x === imgData.width - 1 || y === imgData.height - 1) {
return;
}
if (isStrong(copy.data[x][y])) {
neighbors = copy.getNeighbors(x, y, 3);
_results = [];
for(i = _i = 0; _i <= 2; i = ++_i){
_results.push(function() {
var _j, _results1;
_results1 = [];
for(j = _j = 0; _j <= 2; j = ++_j){
if (isCandidate(neighbors[i][j])) {
copy.data[x - 1 + i][y - 1 + j] = 255;
_results1.push(traverseEdge(x - 1 + i, y - 1 + j));
} else {
_results1.push(void 0);
}
}
return _results1;
}());
}
return _results;
}
};
copy.eachPixel(3, function(x, y) {
return traverseEdge(x, y);
});
copy.eachPixel(1, function(x, y, current) {
if (!isStrong(current)) {
return copy.data[x][y] = 0;
}
});
return copy;
};
CannyJS.canny = function(param, ht, lt, sigmma, kernelSize) {
var width = param.width, height = param.height, data = param.data;
var blur, imgData, nms, sobel;
if (ht == null) {
ht = 100;
}
if (lt == null) {
lt = 50;
}
if (sigmma == null) {
sigmma = 1.4;
}
if (kernelSize == null) {
kernelSize = 3;
}
imgData = new GrayImageData(width, height);
imgData.loadCanvas(data);
blur = CannyJS.gaussianBlur(imgData, sigmma, kernelSize);
sobel = CannyJS.sobel(blur);
nms = CannyJS.nonMaximumSuppression(sobel);
return CannyJS.hysteresis(nms, ht, lt);
};
// src/core/draw/index.ts
var import_jimp = __toESM(require("jimp"));
var directions = [
0 /* Left */ ,
1 /* LeftTop */ ,
2 /* Top */ ,
3 /* TopRight */ ,
4 /* Right */ ,
5 /* RightBottom */ ,
6 /* Bottom */ ,
7 /* BottomLeft */
];
var compose = function() {
for(var _len = arguments.length, fncs = new Array(_len), _key = 0; _key < _len; _key++){
fncs[_key] = arguments[_key];
}
return function() {
for(var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++){
args[_key] = arguments[_key];
}
return fncs.reduce(function(p, n, i) {
return i ? n(p) : n.apply(void 0, _toConsumableArray(p));
}, args);
};
};
var getPointByDirection = function(param, dirction) {
var _param = _slicedToArray(param, 2), x = _param[0], y = _param[1];
switch(dirction){
case 0 /* Left */ :
return [
x - 1,
y
];
case 1 /* LeftTop */ :
return [
x - 1,
y - 1
];
case 2 /* Top */ :
return [
x,
y - 1
];
case 3 /* TopRight */ :
return [
x + 1,
y - 1
];
case 4 /* Right */ :
return [
x + 1,
y
];
case 5 /* RightBottom */ :
return [
x + 1,
y + 1
];
case 6 /* Bottom */ :
return [
x,
y + 1
];
case 7 /* BottomLeft */ :
return [
x - 1,
y + 1
];
}
};
var getPoints = function(imgData, w, h) {
var pointMap = /* @__PURE__ */ new Map();
for(var y = h - 1; y >= 0; y--){
for(var x = w - 1; x >= 0; x--){
var i = x * 4 + y * w * 4;
if (imgData[i] === 255) pointMap.set("".concat(x, "-").concat(y), [
x,
y
]);
}
}
return pointMap;
};
var getLines = function(pointMap) {
var pointCache = /* @__PURE__ */ new Map();
var lines = [];
var random = Math.random;
var _iteratorNormalCompletion = true, _didIteratorError = false, _iteratorError = undefined;
try {
var _loop = function() {
var _step_value = _slicedToArray(_step.value, 2), x = _step_value[0], y = _step_value[1];
if (pointCache.has("".concat(x, "-").concat(y))) return "continue";
directions.sort(function() {
return random() - random();
});
var line = [];
var start = [
x,
y
];
line.push(start);
pointCache.set("".concat(x, "-").concat(y), true);
var i = 0;
while(i < directions.length){
var _getPointByDirection = _slicedToArray(getPointByDirection(start, directions[i]), 2), x2 = _getPointByDirection[0], y2 = _getPointByDirection[1];
if (!pointMap.has("".concat(x2, "-").concat(y2)) || pointCache.has("".concat(x2, "-").concat(y2))) {
i++;
continue;
}
line.push(start = [
x2,
y2
]);
pointCache.set("".concat(x2, "-").concat(y2), true);
}
if (line.length > 2) {
lines.push(line);
}
};
for(var _iterator = pointMap.values()[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true)_loop();
} catch (err) {
_didIteratorError = true;
_iteratorError = err;
} finally{
try {
if (!_iteratorNormalCompletion && _iterator.return != null) {
_iterator.return();
}
} finally{
if (_didIteratorError) {
throw _iteratorError;
}
}
}
return lines;
};
var createPolyLines = function(lines) {
return lines.map(function(line) {
return '<polyline style="--offset:'.concat(line.length, '" points="').concat(line.map(function(point) {
return point.join(",");
}).join(" "), '" fill="none" ></polyline>');
}).join("");
};
var getPolyLines = compose(getPoints, getLines, createPolyLines);
function draw_default(filePath, params) {
return _draw_default.apply(this, arguments);
}
function _draw_default() {
_draw_default = _asyncToGenerator(function(filePath, params) {
var _params_w, w, _params_h, h, img, width, height, scaleImg, width_, height_, canny, content;
return __generator(this, function(_state) {
switch(_state.label){
case 0:
_params_w = params.w, w = _params_w === void 0 ? 400 : _params_w, _params_h = params.h, h = _params_h === void 0 ? import_jimp.default.AUTO : _params_h;
return [
4,
import_jimp.default.read(filePath)
];
case 1:
img = _state.sent();
width = img.getWidth();
height = img.getHeight();
scaleImg = img.resize(+w, +h);
width_ = scaleImg.getWidth();
height_ = scaleImg.getHeight();
canny = CannyJS.canny({
width: width_,
height: height_,
data: scaleImg.bitmap.data
}, 80, 10, 1.4, 3);
content = getPolyLines(canny.toImageDataArray(), width_, height_);
return [
2,
{
content: content,
width: width,
height: height,
width_: width_,
height_: height_
}
];
}
});
});
return _draw_default.apply(this, arguments);
}
// src/core/cucoloris.ts
var import_potrace = __toESM(require("potrace"));
var import_jimp2 = __toESM(require("jimp"));
var defaultOptions = {
background: "#fff",
color: "#c7d4d8",
threshold: 100
};
function cucoloris_default(filePath, params) {
return _cucoloris_default.apply(this, arguments);
}
function _cucoloris_default() {
_cucoloris_default = _asyncToGenerator(function(filePath, params) {
var _params_w, w, _params_h, h, image, img, trace, options, content;
return __generator(this, function(_state) {
switch(_state.label){
case 0:
_params_w = params.w, w = _params_w === void 0 ? 400 : _params_w, _params_h = params.h, h = _params_h === void 0 ? import_jimp2.default.AUTO : _params_h;
return [
4,
import_jimp2.default.read(filePath)
];
case 1:
image = _state.sent();
img = image.resize(+w, +h);
trace = new import_potrace.default.Potrace();
options = _objectSpread({}, defaultOptions, params);
options.threshold = Number(options.threshold);
trace.setParameters(options);
return [
4,
new Promise(function(r) {
trace.loadImage(img.bitmap, function() {
r(trace.getPathTag());
});
})
];
case 2:
content = _state.sent();
return [
2,
{
content: content,
width: img.bitmap.width,
height: img.bitmap.height
}
];
}
});
});
return _cucoloris_default.apply(this, arguments);
}
// src/core/lqip.ts
var import_jimp3 = __toESM(require("jimp"));
function lqip_default(filePath, params) {
return _lqip_default.apply(this, arguments);
}
function _lqip_default() {
_lqip_default = _asyncToGenerator(function(filePath, params) {
var _params_w, w, _params_h, h, _Array_from, _Array_from_, type, image, width, height, img, buffer, content;
return __generator(this, function(_state) {
switch(_state.label){
case 0:
_params_w = params.w, w = _params_w === void 0 ? 20 : _params_w, _params_h = params.h, h = _params_h === void 0 ? import_jimp3.default.AUTO : _params_h;
_Array_from = _slicedToArray(Array.from(filePath.matchAll(/\.(jpg|jpeg|png|gif|webp)/g)), 1), _Array_from_ = _slicedToArray(_Array_from[0], 2), type = _Array_from_[1];
return [
4,
import_jimp3.default.read(filePath)
];
case 1:
image = _state.sent();
width = image.getWidth();
height = image.getHeight();
img = image.resize(+w, +h);
return [
4,
img.getBufferAsync(mimeType[type])
];
case 2:
buffer = _state.sent();
content = "data:".concat(mimeType[type], ";base64,").concat(buffer.toString("base64"));
return [
2,
{
width: width,
height: height,
content: content
}
];
}
});
});
return _lqip_default.apply(this, arguments);
}
// src/core/sqip.ts
var import_sqip = __toESM(require("sqip"));
var detaultOptions = {
numberOfPrimitives: 20,
blur: 2,
mode: 0
};
function sqip_default(filename, params) {
return _sqip_default.apply(this, arguments);
}
function _sqip_default() {
_sqip_default = _asyncToGenerator(function(filename, params) {
var _ref, svg, data;
return __generator(this, function(_state) {
switch(_state.label){
case 0:
return [
4,
(0, import_sqip.default)(_objectSpread({
filename: filename
}, detaultOptions, params))
];
case 1:
_ref = _state.sent(), svg = _ref.final_svg, data = _ref.img_dimensions;
return [
2,
{
content: svg.replace("</svg>", "").replace(/<svg([^<]+)/g, ""),
width: data.width,
height: data.height
}
];
}
});
});
return _sqip_default.apply(this, arguments);
}
// src/core/blurhash.ts
var import_jimp4 = __toESM(require("jimp"));
var import_blurhash = require("blurhash");
var import_upng_js = __toESM(require("upng-js"));
var import_base64_arraybuffer = require("base64-arraybuffer");
function blurhash_default(filePath, params) {
return _blurhash_default.apply(this, arguments);
}
function _blurhash_default() {
_blurhash_default = _asyncToGenerator(function(filePath, params) {
var _params_w, w, _params_h, h, _params_componentX, componentX, _params_componentY, componentY, punch, defaultHash, image, width, height, img, nw, nh, hash, bitmap, png, content;
return __generator(this, function(_state) {
switch(_state.label){
case 0:
_params_w = params.w, w = _params_w === void 0 ? 20 : _params_w, _params_h = params.h, h = _params_h === void 0 ? import_jimp4.default.AUTO : _params_h, _params_componentX = params.componentX, componentX = _params_componentX === void 0 ? 4 : _params_componentX, _params_componentY = params.componentY, componentY = _params_componentY === void 0 ? 4 : _params_componentY, punch = params.punch, defaultHash = params.hash;
return [
4,
import_jimp4.default.read(filePath)
];
case 1:
image = _state.sent();
width = image.getWidth();
height = image.getHeight();
img = image.resize(+w, +h);
nw = img.getWidth();
nh = img.getHeight();
hash = defaultHash || (0, import_blurhash.encode)(Uint8ClampedArray.from(img.bitmap.data), nw, nh, componentX, componentY);
bitmap = (0, import_blurhash.decode)(hash, nw, nh, punch);
png = import_upng_js.default.encode([
bitmap
], nw, nh, 256);
content = "data:image/png;base64,".concat((0, import_base64_arraybuffer.encode)(png));
return [
2,
{
width: width,
height: height,
content: content
}
];
}
});
});
return _blurhash_default.apply(this, arguments);
}
// src/core/index.ts
var import_webp_converter = __toESM(require("webp-converter"));
var path = __toESM(require("path"));
var import_fs = require("fs");
var import_unplugin = require("unplugin");
var import_node_fetch = __toESM(require("node-fetch"));
var outputDir = path.join(process.cwd(), "node_modules", "magic-img-output");
var mimeType = /* @__PURE__ */ function(mimeType2) {
mimeType2["jpeg"] = "image/jpeg";
mimeType2["jpg"] = "image/jpeg";
mimeType2["png"] = "image/png";
mimeType2["gif"] = "image/gif";
return mimeType2;
}(mimeType || {});
try {
(0, import_fs.rmSync)(outputDir, {
recursive: true,
force: true
});
} catch (e) {
console.log(e);
} finally{
(0, import_fs.mkdirSync)(outputDir);
}
var core_default = (0, import_unplugin.createUnplugin)(function() {
var options = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : {}, meta = arguments.length > 1 ? arguments[1] : void 0;
import_webp_converter.default.grant_permission();
var asyncTaskCacheMap = /* @__PURE__ */ new Map();
var cacheMap = /* @__PURE__ */ new Map();
var includeReg = /magic=(draw|cucoloris|lqip|sqip|blurhash)/;
var magicReg = /([^?]+)\?(.+)/g;
var pathReg = /('|")([^'"?]+)/g;
var isRemoteUrl = function(path2) {
return path2.includes("magic-img@");
};
var transformMap = {
draw: draw_default,
cucoloris: cucoloris_default,
lqip: lqip_default,
sqip: sqip_default,
blurhash: blurhash_default
};
function loadImg(url) {
return _loadImg.apply(this, arguments);
}
function _loadImg() {
_loadImg = _asyncToGenerator(function(url) {
var res, resourceType, suffix, aBuffer, buffer, filePath;
return __generator(this, function(_state) {
switch(_state.label){
case 0:
return [
4,
(0, import_node_fetch.default)(url)
];
case 1:
res = _state.sent();
resourceType = res.headers.get("content-type");
suffix = ".".concat(mimeType[resourceType] || "jpg");
return [
4,
res.arrayBuffer()
];
case 2:
aBuffer = _state.sent();
buffer = Buffer.from(aBuffer);
filePath = path.join(outputDir, "".concat(Date.now()).concat(suffix));
return [
4,
import_fs.promises.writeFile(filePath, buffer)
];
case 3:
_state.sent();
return [
2,
filePath
];
}
});
});
return _loadImg.apply(this, arguments);
}
function decodeWebp(filePath) {
return _decodeWebp.apply(this, arguments);
}
function _decodeWebp() {
_decodeWebp = _asyncToGenerator(function(filePath) {
var output;
return __generator(this, function(_state) {
switch(_state.label){
case 0:
if (!filePath.includes(".webp")) return [
2,
filePath
];
output = path.join(outputDir, "".concat(Date.now(), ".jpg"));
return [
4,
import_webp_converter.default.dwebp(filePath, output, "-o")
];
case 1:
_state.sent();
return [
2,
output
];
}
});
});
return _decodeWebp.apply(this, arguments);
}
function getAsyncRes(taskId, task) {
return _getAsyncRes.apply(this, arguments);
}
function _getAsyncRes() {
_getAsyncRes = _asyncToGenerator(function(taskId, task) {
return __generator(this, function(_state) {
switch(_state.label){
case 0:
if (!asyncTaskCacheMap.get(taskId)) {
asyncTaskCacheMap.set(taskId, task());
}
return [
4,
asyncTaskCacheMap.get(taskId)
];
case 1:
return [
2,
_state.sent()
];
}
});
});
return _getAsyncRes.apply(this, arguments);
}
function transform_(code, id) {
return _transform_.apply(this, arguments);
}
function _transform_() {
_transform_ = _asyncToGenerator(function(code, id) {
var isRemote, _Array_from, tmp, _ref, filePath, tmp1, params, convertFilePath, _tmp, _Object_fromEntries, magic, customParams, _ref1, _ref_width, width, _ref_height, height, _ref_width_, width_, _ref_height_, height_, content, _Array_from1, match, str;
return __generator(this, function(_state) {
switch(_state.label){
case 0:
if (id.includes("virtual_magic-img")) id = decodeURIComponent(id);
if (cacheMap.has(id)) return [
2,
cacheMap.get(id)
];
isRemote = isRemoteUrl(id);
_Array_from = _slicedToArray(Array.from(id.matchAll(isRemote ? /magic-img@(.+)\?(.+)/g : magicReg)), 1), tmp = _Array_from[0], _ref = _slicedToArray(tmp === void 0 ? [] : tmp, 3), filePath = _ref[1], tmp1 = _ref[2], params = tmp1 === void 0 ? {} : tmp1;
convertFilePath = filePath;
_tmp = isRemote;
if (!_tmp) return [
3,
2
];
return [
4,
getAsyncRes(convertFilePath, function() {
return loadImg(convertFilePath);
})
];
case 1:
_tmp = convertFilePath = _state.sent();
_state.label = 2;
case 2:
_tmp;
return [
4,
getAsyncRes(convertFilePath, function() {
return decodeWebp(convertFilePath);
})
];
case 3:
convertFilePath = _state.sent();
_Object_fromEntries = Object.fromEntries(new URLSearchParams(params).entries()), magic = _Object_fromEntries.magic, customParams = _objectWithoutProperties(_Object_fromEntries, [
"magic"
]);
return [
4,
transformMap[magic](convertFilePath, _objectSpread({}, options[magic], customParams))
];
case 4:
_ref1 = _state.sent(), _ref_width = _ref1.width, width = _ref_width === void 0 ? 0 : _ref_width, _ref_height = _ref1.height, height = _ref_height === void 0 ? 0 : _ref_height, _ref_width_ = _ref1.width_, width_ = _ref_width_ === void 0 ? 0 : _ref_width_, _ref_height_ = _ref1.height_, height_ = _ref_height_ === void 0 ? 0 : _ref_height_, content = _ref1.content;
_Array_from1 = _slicedToArray(Array.from(code.matchAll(pathReg)), 1), match = _Array_from1[0];
str = "const src = ";
if (isRemote) {
str += '"'.concat(filePath, '"');
} else if (code.includes("__webpack_public_path__")) {
str += '__webpack_public_path__ + "'.concat(match[2], '"');
} else {
str += '"'.concat(match[2].endsWith("$_") ? match[2].slice(0, match[2].length - 2) : match[2], '"');
}
cacheMap.set(id, "\n ".concat(str, "\n export default JSON.stringify({\n src,\n magic: '").concat(magic, "',\n width: ").concat(width, ",\n height: ").concat(height, ",\n width_: ").concat(width_, ",\n height_: ").concat(height_, ",\n content: '").concat(content, "',\n })"));
return [
2,
cacheMap.get(id)
];
}
});
});
return _transform_.apply(this, arguments);
}
return {
name: "unplugin-magic-img",
resolveId: function resolveId(source) {
if (!isRemoteUrl(source)) return null;
return "\x00" + source;
},
loadInclude: function loadInclude(id) {
return isRemoteUrl(id);
},
load: function load(id) {
return _asyncToGenerator(function() {
var _tmp;
return __generator(this, function(_state) {
switch(_state.label){
case 0:
_tmp = {};
return [
4,
transform_("", id)
];
case 1:
return [
2,
(_tmp.code = _state.sent(), _tmp.moduleSideEffects = false, _tmp)
];
}
});
})();
},
transformInclude: function transformInclude(id) {
return includeReg.test(id);
},
transform: transform_
};
});
// src/vite.ts
var vite_default = core_default.vite;
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {});