style: fix formatting via prettier

This commit is contained in:
2026-08-28 14:29:54 +05:00
parent 10278981ba
commit ada96b3534
124 changed files with 8211 additions and 5662 deletions
+53 -35
View File
@@ -1,39 +1,53 @@
import { describe, expect, it } from 'vitest';
import { rotate90, sampleBilinear } from './geometry';
import { rotateFreeImage, skewImage, transformImage, zoomImage } from './affine';
import { makeImage } from './test-helpers';
import { describe, expect, it } from "vitest";
import { rotate90, sampleBilinear } from "./geometry";
import {
rotateFreeImage,
skewImage,
transformImage,
zoomImage,
} from "./affine";
import { makeImage } from "./test-helpers";
describe('sampleBilinear', () => {
it('целые координаты возвращают точный пиксель', () => {
describe("sampleBilinear", () => {
it("целые координаты возвращают точный пиксель", () => {
const img = makeImage(2, 1, [
[255, 0, 0, 255],
[0, 0, 255, 255]
[0, 0, 255, 255],
]);
expect(sampleBilinear(img, 0, 0)).toEqual([255, 0, 0, 255]);
expect(sampleBilinear(img, 1, 0)).toEqual([0, 0, 255, 255]);
});
it('дробная координата интерполирует', () => {
it("дробная координата интерполирует", () => {
const img = makeImage(2, 1, [
[0, 0, 0, 255],
[200, 200, 200, 255]
[200, 200, 200, 255],
]);
const [r] = sampleBilinear(img, 0.5, 0);
expect(r).toBeCloseTo(100, 0);
});
it('координаты за краем клампятся', () => {
it("координаты за краем клампятся", () => {
const img = makeImage(1, 1, [[7, 7, 7, 255]]);
expect(sampleBilinear(img, -10, -10)).toEqual([7, 7, 7, 255]);
});
});
describe('rotateFreeImage', () => {
it('поворот на 180° даёт размеры не меньше исходных и непустой результат', () => {
describe("rotateFreeImage", () => {
it("поворот на 180° даёт размеры не меньше исходных и непустой результат", () => {
const img = makeImage(4, 3, [
[255, 0, 0, 255], [0, 255, 0, 255], [0, 0, 255, 255], [255, 255, 0, 255],
[128, 128, 128, 255], [64, 64, 64, 255], [32, 32, 32, 255], [200, 200, 200, 255],
[10, 20, 30, 255], [40, 50, 60, 255], [70, 80, 90, 255], [100, 100, 100, 255]
[255, 0, 0, 255],
[0, 255, 0, 255],
[0, 0, 255, 255],
[255, 255, 0, 255],
[128, 128, 128, 255],
[64, 64, 64, 255],
[32, 32, 32, 255],
[200, 200, 200, 255],
[10, 20, 30, 255],
[40, 50, 60, 255],
[70, 80, 90, 255],
[100, 100, 100, 255],
]);
const out = rotateFreeImage(img, 180);
expect(out.width).toBeGreaterThanOrEqual(img.width);
@@ -46,12 +60,8 @@ describe('rotateFreeImage', () => {
expect(opaque / total).toBeGreaterThan(0.8);
});
it('поворот квадрата на 360° близок к оригиналу', () => {
const img = makeImage(
5,
5,
new Array(25).fill([200, 100, 50, 255])
);
it("поворот квадрата на 360° близок к оригиналу", () => {
const img = makeImage(5, 5, new Array(25).fill([200, 100, 50, 255]));
const out = rotateFreeImage(img, 360);
expect(out.width).toBeGreaterThanOrEqual(5);
expect(out.height).toBeGreaterThanOrEqual(5);
@@ -59,15 +69,17 @@ describe('rotateFreeImage', () => {
for (let x = 0; x < 5; x++) {
const di = (y * out.width + x) * 4;
for (let ch = 0; ch < 4; ch++) {
expect(Math.abs(out.data[di + ch] - img.data[(y * 5 + x) * 4 + ch])).toBeLessThanOrEqual(4);
expect(
Math.abs(out.data[di + ch] - img.data[(y * 5 + x) * 4 + ch]),
).toBeLessThanOrEqual(4);
}
}
}
});
});
describe('skewImage', () => {
it('наклон X=45° расширяет холст до w+h−1 и сдвигает строки вправо', () => {
describe("skewImage", () => {
it("наклон X=45° расширяет холст до w+h−1 и сдвигает строки вправо", () => {
const img = makeImage(2, 2, new Array(4).fill([255, 0, 0, 255]));
const out = skewImage(img, 45, 0);
expect(out.width).toBe(3);
@@ -76,16 +88,20 @@ describe('skewImage', () => {
for (let i = 3; i < out.data.length; i += 4) {
if (out.data[i] === 255) {
opaque++;
expect([out.data[i - 3], out.data[i - 2], out.data[i - 1]]).toEqual([255, 0, 0]);
expect([out.data[i - 3], out.data[i - 2], out.data[i - 1]]).toEqual([
255, 0, 0,
]);
}
}
expect(opaque).toBe(4);
});
it('углы 0° — тождественное преобразование', () => {
it("углы 0° — тождественное преобразование", () => {
const img = makeImage(2, 2, [
[255, 0, 0, 255], [0, 255, 0, 255],
[0, 0, 255, 255], [128, 128, 128, 255]
[255, 0, 0, 255],
[0, 255, 0, 255],
[0, 0, 255, 255],
[128, 128, 128, 255],
]);
const out = skewImage(img, 0, 0);
expect(out.width).toBe(2);
@@ -93,22 +109,24 @@ describe('skewImage', () => {
});
});
describe('transformImage — заливка фона', () => {
it('сдвиг с белым фоном заполняет освободившийся край', () => {
describe("transformImage — заливка фона", () => {
it("сдвиг с белым фоном заполняет освободившийся край", () => {
const img = makeImage(2, 2, [
[255, 0, 0, 255], [0, 255, 0, 255],
[0, 0, 255, 255], [128, 128, 128, 255]
[255, 0, 0, 255],
[0, 255, 0, 255],
[0, 0, 255, 255],
[128, 128, 128, 255],
]);
const out = transformImage(img, [1, 0, 0, 1, -1, 0], 2, 2, '#ffffff');
const out = transformImage(img, [1, 0, 0, 1, -1, 0], 2, 2, "#ffffff");
expect(out.width).toBe(2);
expect(out.height).toBe(2);
for (let y = 0; y < 2; y++) {
const di = (y * 2) * 4;
const di = y * 2 * 4;
expect([...out.data.slice(di, di + 4)]).toEqual([255, 255, 255, 255]);
}
});
it('без фона освободившийся край остаётся прозрачным', () => {
it("без фона освободившийся край остаётся прозрачным", () => {
const img = makeImage(2, 2, new Array(4).fill([10, 20, 30, 255]));
const out = transformImage(img, [1, 0, 0, 1, -1, 0], 2, 2);
expect(out.data[3]).toBe(0);
+25 -11
View File
@@ -1,14 +1,14 @@
import { parseHex } from './alpha';
import { ToolError } from './errors';
import { clonePixelImage, createPixelImage, type PixelImage } from './types';
import { sampleBilinear } from './geometry';
import { parseHex } from "./alpha";
import { ToolError } from "./errors";
import { clonePixelImage, createPixelImage, type PixelImage } from "./types";
import { sampleBilinear } from "./geometry";
export type AffineMatrix = [number, number, number, number, number, number];
export function invertAffine([a, b, c, d, e, f]: AffineMatrix): AffineMatrix {
const det = a * d - b * c;
if (Math.abs(det) < 1e-12) {
throw new ToolError('errors.badTransform');
throw new ToolError("errors.badTransform");
}
const ia = d / det;
const ib = -b / det;
@@ -24,7 +24,7 @@ export function transformImage(
dstToSrc: AffineMatrix,
outWidth: number,
outHeight: number,
bgHex?: string
bgHex?: string,
): PixelImage {
const [a, b, c, d, e, f] = dstToSrc;
const out = createPixelImage(outWidth, outHeight);
@@ -34,7 +34,12 @@ export function transformImage(
const sx = a * x + c * y + e;
const sy = b * x + d * y + f;
const di = (y * outWidth + x) * 4;
if (sx < -EPS || sy < -EPS || sx > img.width - 1 + EPS || sy > img.height - 1 + EPS) {
if (
sx < -EPS ||
sy < -EPS ||
sx > img.width - 1 + EPS ||
sy > img.height - 1 + EPS
) {
if (bg) {
out.data[di] = bg[0];
out.data[di + 1] = bg[1];
@@ -72,7 +77,7 @@ function centeredTransform(img: PixelImage, forward: AffineMatrix): PixelImage {
[0.5, 0.5],
[img.width - 0.5, 0.5],
[0.5, img.height - 0.5],
[img.width - 0.5, img.height - 0.5]
[img.width - 0.5, img.height - 0.5],
]) {
const qx = forward[0] * px + forward[2] * py + forward[4];
const qy = forward[1] * px + forward[3] * py + forward[5];
@@ -85,14 +90,23 @@ function centeredTransform(img: PixelImage, forward: AffineMatrix): PixelImage {
const outH = Math.round(maxY - minY) + 1;
const tx = inv[0] * minX + inv[2] * minY - 0.5;
const ty = inv[1] * minX + inv[3] * minY - 0.5;
return transformImage(img, [inv[0], inv[1], inv[2], inv[3], tx, ty], outW, outH);
return transformImage(
img,
[inv[0], inv[1], inv[2], inv[3], tx, ty],
outW,
outH,
);
}
export function skewImage(img: PixelImage, degX: number, degY: number): PixelImage {
export function skewImage(
img: PixelImage,
degX: number,
degY: number,
): PixelImage {
const kx = Math.tan((degX * Math.PI) / 180);
const ky = Math.tan((degY * Math.PI) / 180);
if (!Number.isFinite(kx) || !Number.isFinite(ky)) {
throw new ToolError('errors.skewAngle');
throw new ToolError("errors.skewAngle");
}
return centeredTransform(img, [1, ky, kx, 1, 0, 0]);
}
+81 -82
View File
@@ -1,4 +1,4 @@
import { describe, expect, it } from 'vitest';
import { describe, expect, it } from "vitest";
import {
colorMask,
extractAlphaMask,
@@ -8,53 +8,52 @@ import {
parseHex,
removeColorToAlpha,
roundCorners,
setAlphaChannel
} from './alpha';
import { makeImage } from './test-helpers';
setAlphaChannel,
} from "./alpha";
import { makeImage } from "./test-helpers";
describe('hardenAlpha', () => {
it('бинаризует альфу по порогу, RGB не трогает', () => {
describe("hardenAlpha", () => {
it("бинаризует альфу по порогу, RGB не трогает", () => {
const out = hardenAlpha(
makeImage(2, 1, [
[10, 20, 30, 100],
[40, 50, 60, 200]
[40, 50, 60, 200],
]),
50
50,
);
expect([...out.data]).toEqual([
10, 20, 30, 0,
40, 50, 60, 255
]);
expect([...out.data]).toEqual([10, 20, 30, 0, 40, 50, 60, 255]);
});
});
describe('setAlphaChannel', () => {
it('задаёт константную альфу', () => {
const out = setAlphaChannel(makeImage(2, 1, [
[1, 2, 3, 255],
[4, 5, 6, 0]
]), 50);
describe("setAlphaChannel", () => {
it("задаёт константную альфу", () => {
const out = setAlphaChannel(
makeImage(2, 1, [
[1, 2, 3, 255],
[4, 5, 6, 0],
]),
50,
);
expect(out.data[3]).toBe(128);
expect(out.data[7]).toBe(128);
expect(out.data[0]).toBe(1);
});
});
describe('extractAlphaMask', () => {
it('переводит альфу в чёрно-белую непрозрачную маску', () => {
const out = extractAlphaMask(makeImage(2, 1, [
[10, 20, 30, 255],
[40, 50, 60, 0]
]));
expect([...out.data]).toEqual([
255, 255, 255, 255,
0, 0, 0, 255
]);
describe("extractAlphaMask", () => {
it("переводит альфу в чёрно-белую непрозрачную маску", () => {
const out = extractAlphaMask(
makeImage(2, 1, [
[10, 20, 30, 255],
[40, 50, 60, 0],
]),
);
expect([...out.data]).toEqual([255, 255, 255, 255, 0, 0, 0, 255]);
});
});
describe('roundCorners', () => {
it('срезает углы, центр и середины сторон остаются', () => {
describe("roundCorners", () => {
it("срезает углы, центр и середины сторон остаются", () => {
const img = makeImage(11, 11, new Array(121).fill([100, 100, 100, 255]));
const out = roundCorners(img, 40);
expect(out.data[(0 * 11 + 0) * 4 + 3]).toBe(0);
@@ -62,125 +61,125 @@ describe('roundCorners', () => {
expect(out.data[(5 * 11 + 0) * 4 + 3]).toBe(255);
});
it('нулевой радиус ничего не меняет', () => {
it("нулевой радиус ничего не меняет", () => {
const img = makeImage(2, 2, new Array(4).fill([1, 2, 3, 255]));
expect([...roundCorners(img, 0).data]).toEqual([...img.data]);
});
});
describe('invertAlpha', () => {
it('обращает альфу, RGB не трогает', () => {
describe("invertAlpha", () => {
it("обращает альфу, RGB не трогает", () => {
const out = invertAlpha(makeImage(1, 1, [[10, 20, 30, 128]]));
expect([...out.data]).toEqual([10, 20, 30, 127]);
});
});
describe('removeColorToAlpha', () => {
describe("removeColorToAlpha", () => {
const fixture = () =>
makeImage(2, 1, [
[255, 255, 255, 255],
[255, 0, 0, 255]
[255, 0, 0, 255],
]);
it('обнуляет альфу только у точного совпадения при tolerance=0', () => {
const out = removeColorToAlpha(fixture(), '#ff0000', 0);
it("обнуляет альфу только у точного совпадения при tolerance=0", () => {
const out = removeColorToAlpha(fixture(), "#ff0000", 0);
expect(out.data[3]).toBe(255);
expect(out.data[7]).toBe(0);
expect(out.data[4]).toBe(255);
expect(out.data[5]).toBe(0);
});
it('поддерживает короткую форму и регистр hex', () => {
expect([...removeColorToAlpha(fixture(), '#f00', 0).data.slice(4)]).toEqual([
255, 0, 0, 0
]);
expect([...removeColorToAlpha(fixture(), '#FF0000', 0).data.slice(4)]).toEqual([
255, 0, 0, 0
]);
it("поддерживает короткую форму и регистр hex", () => {
expect([...removeColorToAlpha(fixture(), "#f00", 0).data.slice(4)]).toEqual(
[255, 0, 0, 0],
);
expect([
...removeColorToAlpha(fixture(), "#FF0000", 0).data.slice(4),
]).toEqual([255, 0, 0, 0]);
});
it('tolerance 100% удаляет весь диапазон расстояний', () => {
const out = removeColorToAlpha(fixture(), '#000000', 100);
it("tolerance 100% удаляет весь диапазон расстояний", () => {
const out = removeColorToAlpha(fixture(), "#000000", 100);
expect(out.data[3]).toBe(0);
expect(out.data[7]).toBe(0);
});
it('промежуточный tolerance различает близкие и далёкие цвета', () => {
it("промежуточный tolerance различает близкие и далёкие цвета", () => {
const img = makeImage(2, 1, [
[0, 0, 0, 255],
[128, 128, 128, 255]
[128, 128, 128, 255],
]);
const kept = removeColorToAlpha(img, '#000000', 40);
const removed = removeColorToAlpha(img, '#000000', 60);
const kept = removeColorToAlpha(img, "#000000", 40);
const removed = removeColorToAlpha(img, "#000000", 60);
expect(kept.data[3]).toBe(0);
expect(kept.data[7]).toBe(255);
expect(removed.data[3]).toBe(0);
expect(removed.data[7]).toBe(0);
});
it('не мутирует вход', () => {
it("не мутирует вход", () => {
const img = fixture();
removeColorToAlpha(img, '#ffffff', 100);
expect([...img.data]).toEqual([
255, 255, 255, 255,
255, 0, 0, 255
]);
removeColorToAlpha(img, "#ffffff", 100);
expect([...img.data]).toEqual([255, 255, 255, 255, 255, 0, 0, 255]);
});
});
describe('colorMask', () => {
it('удаляемые пиксели белые, остальные чёрные, маска непрозрачная', () => {
describe("colorMask", () => {
it("удаляемые пиксели белые, остальные чёрные, маска непрозрачная", () => {
const out = colorMask(
makeImage(2, 1, [
[255, 0, 0, 255],
[0, 255, 0, 255]
[0, 255, 0, 255],
]),
'#ff0000',
0
"#ff0000",
0,
);
expect([...out.data]).toEqual([
255, 255, 255, 255,
0, 0, 0, 255
]);
expect([...out.data]).toEqual([255, 255, 255, 255, 0, 0, 0, 255]);
});
it('порог совпадает с removeColorToAlpha', () => {
it("порог совпадает с removeColorToAlpha", () => {
const img = makeImage(2, 1, [
[0, 0, 0, 255],
[128, 128, 128, 255]
[128, 128, 128, 255],
]);
const kept = colorMask(img, '#000000', 40);
const removed = colorMask(img, '#000000', 60);
const kept = colorMask(img, "#000000", 40);
const removed = colorMask(img, "#000000", 60);
expect(kept.data[4]).toBe(0);
expect(removed.data[4]).toBe(255);
});
});
describe('flattenOntoColor', () => {
it('непрозрачный пиксель не меняется, альфа становится 255', () => {
const out = flattenOntoColor(makeImage(1, 1, [[10, 20, 30, 255]]), '#ffffff');
describe("flattenOntoColor", () => {
it("непрозрачный пиксель не меняется, альфа становится 255", () => {
const out = flattenOntoColor(
makeImage(1, 1, [[10, 20, 30, 255]]),
"#ffffff",
);
expect([...out.data]).toEqual([10, 20, 30, 255]);
});
it('полностью прозрачный пиксель становится цветом подложки', () => {
const out = flattenOntoColor(makeImage(1, 1, [[99, 99, 99, 0]]), '#ff8040');
it("полностью прозрачный пиксель становится цветом подложки", () => {
const out = flattenOntoColor(makeImage(1, 1, [[99, 99, 99, 0]]), "#ff8040");
expect([...out.data]).toEqual([255, 128, 64, 255]);
});
it('полупрозрачный пиксель смешивается с подложкой', () => {
const out = flattenOntoColor(makeImage(1, 1, [[10, 20, 30, 128]]), '#ffffff');
it("полупрозрачный пиксель смешивается с подложкой", () => {
const out = flattenOntoColor(
makeImage(1, 1, [[10, 20, 30, 128]]),
"#ffffff",
);
expect([...out.data]).toEqual([132, 137, 142, 255]);
});
});
describe('parseHex', () => {
it('разбирает #rrggbb, rrggbb, #rgb', () => {
expect(parseHex('#ff8040')).toEqual([255, 128, 64]);
expect(parseHex('ff8040')).toEqual([255, 128, 64]);
expect(parseHex('#F80')).toEqual([255, 136, 0]);
describe("parseHex", () => {
it("разбирает #rrggbb, rrggbb, #rgb", () => {
expect(parseHex("#ff8040")).toEqual([255, 128, 64]);
expect(parseHex("ff8040")).toEqual([255, 128, 64]);
expect(parseHex("#F80")).toEqual([255, 136, 0]);
});
it.each(['zzz', '12345', '##ff', ''])('бросает ошибку на "%s"', (bad) => {
it.each(["zzz", "12345", "##ff", ""])('бросает ошибку на "%s"', (bad) => {
expect(() => parseHex(bad)).toThrow(/errors\.badHex/);
});
});
+42 -16
View File
@@ -1,17 +1,22 @@
import { createPixelImage, type PixelImage } from './types';
import { ToolError } from './errors';
import { createPixelImage, type PixelImage } from "./types";
import { ToolError } from "./errors";
const MAX_COLOR_DISTANCE = Math.sqrt(3 * 255 * 255);
export function removeColorToAlpha(
img: PixelImage,
hex: string,
tolerancePercent = 0
tolerancePercent = 0,
): PixelImage {
const [targetR, targetG, targetB] = parseHex(hex);
const tolerance = (clamp(tolerancePercent, 0, 100) / 100) * MAX_COLOR_DISTANCE;
const tolerance =
(clamp(tolerancePercent, 0, 100) / 100) * MAX_COLOR_DISTANCE;
const thresholdSq = tolerance * tolerance;
const out: PixelImage = { width: img.width, height: img.height, data: img.data.slice() };
const out: PixelImage = {
width: img.width,
height: img.height,
data: img.data.slice(),
};
for (let i = 0; i < out.data.length; i += 4) {
const dr = out.data[i] - targetR;
const dg = out.data[i + 1] - targetG;
@@ -25,7 +30,11 @@ export function removeColorToAlpha(
export function setAlphaChannel(img: PixelImage, percent: number): PixelImage {
const alpha = Math.round((clamp(percent, 0, 100) / 100) * 255);
const out: PixelImage = { width: img.width, height: img.height, data: img.data.slice() };
const out: PixelImage = {
width: img.width,
height: img.height,
data: img.data.slice(),
};
for (let i = 3; i < out.data.length; i += 4) {
out.data[i] = alpha;
}
@@ -44,10 +53,19 @@ export function extractAlphaMask(img: PixelImage): PixelImage {
return out;
}
export function roundCorners(img: PixelImage, radiusPercent: number): PixelImage {
const radius = (clamp(radiusPercent, 0, 50) / 100) * (Math.min(img.width, img.height) / 2);
if (radius < 1) return { width: img.width, height: img.height, data: img.data.slice() };
const out: PixelImage = { width: img.width, height: img.height, data: img.data.slice() };
export function roundCorners(
img: PixelImage,
radiusPercent: number,
): PixelImage {
const radius =
(clamp(radiusPercent, 0, 50) / 100) * (Math.min(img.width, img.height) / 2);
if (radius < 1)
return { width: img.width, height: img.height, data: img.data.slice() };
const out: PixelImage = {
width: img.width,
height: img.height,
data: img.data.slice(),
};
const r2 = radius * radius;
for (let y = 0; y < out.height; y++) {
for (let x = 0; x < out.width; x++) {
@@ -74,7 +92,10 @@ export function invertAlpha(img: PixelImage): PixelImage {
return out;
}
export function hardenAlpha(img: PixelImage, thresholdPercent: number): PixelImage {
export function hardenAlpha(
img: PixelImage,
thresholdPercent: number,
): PixelImage {
const threshold = (clamp(thresholdPercent, 0, 100) / 100) * 255;
const out = createPixelImage(img.width, img.height);
for (let i = 0; i < out.data.length; i += 4) {
@@ -86,9 +107,14 @@ export function hardenAlpha(img: PixelImage, thresholdPercent: number): PixelIma
return out;
}
export function colorMask(img: PixelImage, hex: string, tolerancePercent = 0): PixelImage {
export function colorMask(
img: PixelImage,
hex: string,
tolerancePercent = 0,
): PixelImage {
const [targetR, targetG, targetB] = parseHex(hex);
const tolerance = (clamp(tolerancePercent, 0, 100) / 100) * MAX_COLOR_DISTANCE;
const tolerance =
(clamp(tolerancePercent, 0, 100) / 100) * MAX_COLOR_DISTANCE;
const thresholdSq = tolerance * tolerance;
const out = createPixelImage(img.width, img.height);
for (let i = 0; i < out.data.length; i += 4) {
@@ -121,20 +147,20 @@ export function flattenOntoColor(img: PixelImage, hex: string): PixelImage {
export function parseHex(hex: string): [number, number, number] {
const match = /^#?([0-9a-f]{3}|[0-9a-f]{6})$/i.exec(hex.trim());
if (!match) {
throw new ToolError('errors.badHex', { value: hex });
throw new ToolError("errors.badHex", { value: hex });
}
const digits = match[1];
if (digits.length === 3) {
return [
parseInt(digits[0] + digits[0], 16),
parseInt(digits[1] + digits[1], 16),
parseInt(digits[2] + digits[2], 16)
parseInt(digits[2] + digits[2], 16),
];
}
return [
parseInt(digits.slice(0, 2), 16),
parseInt(digits.slice(2, 4), 16),
parseInt(digits.slice(4, 6), 16)
parseInt(digits.slice(4, 6), 16),
];
}
+39 -28
View File
@@ -1,76 +1,87 @@
import { describe, expect, it } from 'vitest';
import { describe, expect, it } from "vitest";
import {
hasTransparency,
imageInfo,
isGrayscale,
orientationOf
} from './analyze';
import { makeImage } from './test-helpers';
orientationOf,
} from "./analyze";
import { makeImage } from "./test-helpers";
describe('imageInfo', () => {
it('находит полупрозрачные пиксели и считает уникальные RGBA-цвета', () => {
describe("imageInfo", () => {
it("находит полупрозрачные пиксели и считает уникальные RGBA-цвета", () => {
const info = imageInfo(
makeImage(2, 2, [
[0, 0, 0, 255],
[0, 0, 0, 255],
[255, 0, 0, 128],
[255, 0, 0, 128]
])
[255, 0, 0, 128],
]),
);
expect(info).toEqual({ width: 2, height: 2, hasAlpha: true, colorCount: 2 });
expect(info).toEqual({
width: 2,
height: 2,
hasAlpha: true,
colorCount: 2,
});
});
it('полностью непрозрачное изображение — hasAlpha false', () => {
it("полностью непрозрачное изображение — hasAlpha false", () => {
const info = imageInfo(
makeImage(2, 1, [
[10, 20, 30, 255],
[40, 50, 60, 255]
])
[40, 50, 60, 255],
]),
);
expect(info.hasAlpha).toBe(false);
expect(info.colorCount).toBe(2);
});
it('разная альфа означает разные цвета', () => {
it("разная альфа означает разные цвета", () => {
const info = imageInfo(
makeImage(2, 1, [
[255, 0, 0, 255],
[255, 0, 0, 128]
])
[255, 0, 0, 128],
]),
);
expect(info.hasAlpha).toBe(true);
expect(info.colorCount).toBe(2);
});
it('возвращает корректные размеры неквадрата', () => {
it("возвращает корректные размеры неквадрата", () => {
const info = imageInfo(makeImage(5, 3, new Array(15).fill([1, 2, 3, 4])));
expect(info.width).toBe(5);
expect(info.height).toBe(3);
});
});
describe('isGrayscale', () => {
it('серые пиксели — монохром', () => {
describe("isGrayscale", () => {
it("серые пиксели — монохром", () => {
expect(isGrayscale(makeImage(1, 1, [[10, 10, 10, 255]]))).toBe(true);
});
it('цветной пиксель ломает монохром', () => {
it("цветной пиксель ломает монохром", () => {
expect(isGrayscale(makeImage(1, 1, [[10, 11, 10, 255]]))).toBe(false);
});
});
describe('hasTransparency', () => {
it('альфа ниже 255 — прозрачность есть', () => {
describe("hasTransparency", () => {
it("альфа ниже 255 — прозрачность есть", () => {
expect(hasTransparency(makeImage(1, 1, [[0, 0, 0, 254]]))).toBe(true);
});
it('все пиксели непрозрачны', () => {
it("все пиксели непрозрачны", () => {
expect(hasTransparency(makeImage(1, 1, [[0, 0, 0, 255]]))).toBe(false);
});
});
describe('orientationOf', () => {
it('определяет ориентацию', () => {
expect(orientationOf(makeImage(2, 3, new Array(6).fill([1, 1, 1, 1])))).toBe('portrait');
expect(orientationOf(makeImage(3, 2, new Array(6).fill([1, 1, 1, 1])))).toBe('landscape');
expect(orientationOf(makeImage(2, 2, new Array(4).fill([1, 1, 1, 1])))).toBe('square');
describe("orientationOf", () => {
it("определяет ориентацию", () => {
expect(
orientationOf(makeImage(2, 3, new Array(6).fill([1, 1, 1, 1]))),
).toBe("portrait");
expect(
orientationOf(makeImage(3, 2, new Array(6).fill([1, 1, 1, 1]))),
).toBe("landscape");
expect(
orientationOf(makeImage(2, 2, new Array(4).fill([1, 1, 1, 1]))),
).toBe("square");
});
});
});
+15 -7
View File
@@ -1,4 +1,4 @@
import type { PixelImage } from './types';
import type { PixelImage } from "./types";
export type ImageInfo = {
width: number;
@@ -22,12 +22,20 @@ export function imageInfo(img: PixelImage): ImageInfo {
0;
seen.add(key);
}
return { width: img.width, height: img.height, hasAlpha, colorCount: seen.size };
return {
width: img.width,
height: img.height,
hasAlpha,
colorCount: seen.size,
};
}
export function isGrayscale(img: PixelImage): boolean {
for (let i = 0; i < img.data.length; i += 4) {
if (img.data[i] !== img.data[i + 1] || img.data[i + 1] !== img.data[i + 2]) {
if (
img.data[i] !== img.data[i + 1] ||
img.data[i + 1] !== img.data[i + 2]
) {
return false;
}
}
@@ -41,10 +49,10 @@ export function hasTransparency(img: PixelImage): boolean {
return false;
}
export type Orientation = 'portrait' | 'landscape' | 'square';
export type Orientation = "portrait" | "landscape" | "square";
export function orientationOf(img: PixelImage): Orientation {
if (img.height > img.width) return 'portrait';
if (img.width > img.height) return 'landscape';
return 'square';
if (img.height > img.width) return "portrait";
if (img.width > img.height) return "landscape";
return "square";
}
+75 -64
View File
@@ -1,108 +1,119 @@
import { describe, expect, it } from 'vitest';
import { describe, expect, it } from "vitest";
import {
backgroundMaskPreview,
backgroundRemovalMask,
removeBackground
} from './background';
import { makeImage } from './test-helpers';
removeBackground,
} from "./background";
import { makeImage } from "./test-helpers";
const GREEN = [0, 255, 0, 255];
const RED = [255, 0, 0, 255];
describe('backgroundRemovalMask', () => {
it('глобальный режим удаляет все совпадающие пиксели', () => {
const mask = backgroundRemovalMask(
makeImage(2, 1, [GREEN, RED]),
{ color: '#00ff00', tolerancePercent: 0, outerOnly: false, smoothPasses: 0 }
);
describe("backgroundRemovalMask", () => {
it("глобальный режим удаляет все совпадающие пиксели", () => {
const mask = backgroundRemovalMask(makeImage(2, 1, [GREEN, RED]), {
color: "#00ff00",
tolerancePercent: 0,
outerOnly: false,
smoothPasses: 0,
});
expect([...mask]).toEqual([1, 0]);
});
describe('режим внешних областей', () => {
const ringRedCenterGreen = [
RED, RED, RED,
RED, GREEN, RED,
RED, RED, RED
];
describe("режим внешних областей", () => {
const ringRedCenterGreen = [RED, RED, RED, RED, GREEN, RED, RED, RED, RED];
it('заливка от краёв не достаёт до изолированного совпадающего острова', () => {
const mask = backgroundRemovalMask(
makeImage(3, 3, ringRedCenterGreen),
{ color: '#00ff00', tolerancePercent: 0, outerOnly: true, smoothPasses: 0 }
);
expect(mask[4]).toBe(0);
it("заливка от краёв не достаёт до изолированного совпадающего острова", () => {
const mask = backgroundRemovalMask(makeImage(3, 3, ringRedCenterGreen), {
color: "#00ff00",
tolerancePercent: 0,
outerOnly: true,
smoothPasses: 0,
});
expect(mask[4]).toBe(0);
});
it("глобальный режим удаляет и изолированный остров", () => {
const mask = backgroundRemovalMask(makeImage(3, 3, ringRedCenterGreen), {
color: "#00ff00",
tolerancePercent: 0,
outerOnly: false,
smoothPasses: 0,
});
expect(mask[4]).toBe(1);
expect(mask[0]).toBe(0);
});
});
it('глобальный режим удаляет и изолированный остров', () => {
const mask = backgroundRemovalMask(
makeImage(3, 3, ringRedCenterGreen),
{ color: '#00ff00', tolerancePercent: 0, outerOnly: false, smoothPasses: 0 }
);
expect(mask[4]).toBe(1);
expect(mask[0]).toBe(0);
});
});
it('допуск расширяет захват по цветовому расстоянию', () => {
it("допуск расширяет захват по цветовому расстоянию", () => {
const img = makeImage(2, 1, [
[10, 10, 10, 255],
[128, 128, 128, 255]
[128, 128, 128, 255],
]);
const tight = backgroundRemovalMask(img, {
color: '#000000', tolerancePercent: 40, outerOnly: false, smoothPasses: 0
color: "#000000",
tolerancePercent: 40,
outerOnly: false,
smoothPasses: 0,
});
const wide = backgroundRemovalMask(img, {
color: '#000000', tolerancePercent: 60, outerOnly: false, smoothPasses: 0
color: "#000000",
tolerancePercent: 60,
outerOnly: false,
smoothPasses: 0,
});
expect(tight[1]).toBe(0);
expect(wide[1]).toBe(1);
});
});
describe('smoothMask-поведение через backgroundRemovalMask', () => {
const ringRedCenterGreen = [
RED, RED, RED,
RED, GREEN, RED,
RED, RED, RED
];
const opts = { color: '#00ff00', tolerancePercent: 0, outerOnly: false };
describe("smoothMask-поведение через backgroundRemovalMask", () => {
const ringRedCenterGreen = [RED, RED, RED, RED, GREEN, RED, RED, RED, RED];
const opts = { color: "#00ff00", tolerancePercent: 0, outerOnly: false };
const alphaAtCenter = (img: { data: Uint8ClampedArray }) => img.data[19];
it('без сглаживания центр удалён', () => {
const img = removeBackground(makeImage(3, 3, ringRedCenterGreen), { ...opts, smoothPasses: 0 });
it("без сглаживания центр удалён", () => {
const img = removeBackground(makeImage(3, 3, ringRedCenterGreen), {
...opts,
smoothPasses: 0,
});
expect(alphaAtCenter(img)).toBe(0);
});
it('два прохода мажоритарного фильтра возвращают изолированный пиксель', () => {
const img = removeBackground(makeImage(3, 3, ringRedCenterGreen), { ...opts, smoothPasses: 2 });
it("два прохода мажоритарного фильтра возвращают изолированный пиксель", () => {
const img = removeBackground(makeImage(3, 3, ringRedCenterGreen), {
...opts,
smoothPasses: 2,
});
expect(alphaAtCenter(img)).toBe(255);
});
});
describe('removeBackground', () => {
it('обнуляет альфу удалённых, сохраняет RGB остальных', () => {
const out = removeBackground(
makeImage(2, 1, [GREEN, [5, 6, 7, 200]]),
{ color: '#00ff00', tolerancePercent: 0, outerOnly: false, smoothPasses: 0 }
);
describe("removeBackground", () => {
it("обнуляет альфу удалённых, сохраняет RGB остальных", () => {
const out = removeBackground(makeImage(2, 1, [GREEN, [5, 6, 7, 200]]), {
color: "#00ff00",
tolerancePercent: 0,
outerOnly: false,
smoothPasses: 0,
});
expect(out.data[3]).toBe(0);
expect([...out.data.slice(4, 8)]).toEqual([5, 6, 7, 200]);
});
});
describe('backgroundMaskPreview', () => {
it('белое там, где удаление, чёрное — где остаёмся, всё непрозрачно', () => {
describe("backgroundMaskPreview", () => {
it("белое там, где удаление, чёрное — где остаёмся, всё непрозрачно", () => {
const preview = backgroundMaskPreview(
makeImage(2, 1, [
GREEN,
[9, 9, 9, 60]
]),
{ color: '#00ff00', tolerancePercent: 0, outerOnly: false, smoothPasses: 0 }
makeImage(2, 1, [GREEN, [9, 9, 9, 60]]),
{
color: "#00ff00",
tolerancePercent: 0,
outerOnly: false,
smoothPasses: 0,
},
);
expect([...preview.data]).toEqual([
255, 255, 255, 255,
0, 0, 0, 255
]);
expect([...preview.data]).toEqual([255, 255, 255, 255, 0, 0, 0, 255]);
});
});
+15 -8
View File
@@ -1,5 +1,5 @@
import { parseHex } from './alpha';
import { createPixelImage, type PixelImage } from './types';
import { parseHex } from "./alpha";
import { createPixelImage, type PixelImage } from "./types";
export type BackgroundOptions = {
color: string;
@@ -13,9 +13,10 @@ function buildRawMask(
targetR: number,
targetG: number,
targetB: number,
tolerancePercent: number
tolerancePercent: number,
): Uint8Array {
const tolerance = (clamp(tolerancePercent, 0, 100) / 100) * Math.sqrt(3 * 255 * 255);
const tolerance =
(clamp(tolerancePercent, 0, 100) / 100) * Math.sqrt(3 * 255 * 255);
const thresholdSq = tolerance * tolerance;
const mask = new Uint8Array(img.width * img.height);
for (let i = 0; i < mask.length; i++) {
@@ -61,7 +62,7 @@ export function smoothMask(
mask: Uint8Array,
w: number,
h: number,
passes: number
passes: number,
): Uint8Array {
let current = mask;
const count = clamp(Math.trunc(passes), 0, 8);
@@ -89,7 +90,7 @@ export function smoothMask(
export function backgroundRemovalMask(
img: PixelImage,
options: BackgroundOptions
options: BackgroundOptions,
): Uint8Array {
const [tr, tg, tb] = parseHex(options.color);
const mask = buildRawMask(img, tr, tg, tb, options.tolerancePercent);
@@ -99,7 +100,10 @@ export function backgroundRemovalMask(
return smoothMask(mask, img.width, img.height, options.smoothPasses);
}
export function removeBackground(img: PixelImage, options: BackgroundOptions): PixelImage {
export function removeBackground(
img: PixelImage,
options: BackgroundOptions,
): PixelImage {
const mask = backgroundRemovalMask(img, options);
const out = createPixelImage(img.width, img.height);
for (let i = 0; i < mask.length; i++) {
@@ -112,7 +116,10 @@ export function removeBackground(img: PixelImage, options: BackgroundOptions): P
return out;
}
export function backgroundMaskPreview(img: PixelImage, options: BackgroundOptions): PixelImage {
export function backgroundMaskPreview(
img: PixelImage,
options: BackgroundOptions,
): PixelImage {
const mask = backgroundRemovalMask(img, options);
const out = createPixelImage(img.width, img.height);
for (let i = 0; i < mask.length; i++) {
+14 -17
View File
@@ -1,14 +1,14 @@
import { describe, expect, it } from 'vitest';
import { encodeBmpBytes } from './bmp';
import { makeImage } from './test-helpers';
import { describe, expect, it } from "vitest";
import { encodeBmpBytes } from "./bmp";
import { makeImage } from "./test-helpers";
describe('encodeBmpBytes', () => {
it('пишет заголовки BM и размеры для 2x1 без паддинга-неопределённости', () => {
describe("encodeBmpBytes", () => {
it("пишет заголовки BM и размеры для 2x1 без паддинга-неопределённости", () => {
const bytes = encodeBmpBytes(
makeImage(2, 1, [
[255, 0, 0, 255],
[0, 255, 0, 255]
])
[0, 255, 0, 255],
]),
);
expect([bytes[0], bytes[1]]).toEqual([0x42, 0x4d]);
const view = new DataView(bytes.buffer);
@@ -18,22 +18,19 @@ describe('encodeBmpBytes', () => {
expect(view.getUint16(28, true)).toBe(24);
});
it('хранит пиксели в BGR снизу-вверх с паддингом строки', () => {
it("хранит пиксели в BGR снизу-вверх с паддингом строки", () => {
const bytes = encodeBmpBytes(
makeImage(2, 1, [
[255, 0, 0, 255],
[0, 255, 0, 255]
])
[0, 255, 0, 255],
]),
);
expect([...bytes.slice(54, 60)]).toEqual([
0, 0, 255,
0, 255, 0
]);
expect([...bytes.slice(54, 60)]).toEqual([0, 0, 255, 0, 255, 0]);
expect(bytes[60]).toBe(0);
expect(bytes[61]).toBe(0);
});
it('нижняя строка изображения идёт первой в файле', () => {
it("нижняя строка изображения идёт первой в файле", () => {
const bytes = encodeBmpBytes(
makeImage(4, 2, [
[10, 10, 10, 255],
@@ -43,8 +40,8 @@ describe('encodeBmpBytes', () => {
[50, 50, 50, 255],
[60, 60, 60, 255],
[70, 70, 70, 255],
[80, 80, 80, 255]
])
[80, 80, 80, 255],
]),
);
expect(bytes[54]).toBe(50);
expect(bytes[54 + 12]).toBe(10);
+1 -1
View File
@@ -1,4 +1,4 @@
import type { PixelImage } from './types';
import type { PixelImage } from "./types";
export function encodeBmpBytes(img: PixelImage): Uint8Array<ArrayBuffer> {
const rowSize = Math.ceil((img.width * 3) / 4) * 4;
+21 -19
View File
@@ -1,41 +1,41 @@
import { describe, expect, it } from 'vitest';
import { hexToRgb } from './palette';
import { renderSpace, SPACES } from './channels';
import { makeImage } from './test-helpers';
import { describe, expect, it } from "vitest";
import { hexToRgb } from "./palette";
import { renderSpace, SPACES } from "./channels";
import { makeImage } from "./test-helpers";
describe('преобразования пространств', () => {
it('hsl красного: h=0, s=1, l=0.5', () => {
const [h, s, l] = SPACES.hsl.convert(hexToRgb('#ff0000'));
describe("преобразования пространств", () => {
it("hsl красного: h=0, s=1, l=0.5", () => {
const [h, s, l] = SPACES.hsl.convert(hexToRgb("#ff0000"));
expect(h).toBeCloseTo(0);
expect(s).toBeCloseTo(1);
expect(l).toBeCloseTo(0.5);
});
it('hsv белого: v=1, чёрного: v=0', () => {
it("hsv белого: v=1, чёрного: v=0", () => {
expect(SPACES.hsv.convert({ r: 255, g: 255, b: 255 })[2]).toBeCloseTo(1);
expect(SPACES.hsv.convert({ r: 0, g: 0, b: 0 })[2]).toBe(0);
});
it('hsi серого: s=0', () => {
it("hsi серого: s=0", () => {
const [, s] = SPACES.hsi.convert({ r: 128, g: 128, b: 128 });
expect(s).toBeCloseTo(0);
});
it('cmyk: белый — 0,0,0,0; чёрный — 0,0,0,1', () => {
it("cmyk: белый — 0,0,0,0; чёрный — 0,0,0,1", () => {
const w = SPACES.cmyk.convert({ r: 255, g: 255, b: 255 });
const b = SPACES.cmyk.convert({ r: 0, g: 0, b: 0 });
expect(w.every((v) => Math.abs(v) < 1e-9)).toBe(true);
expect(b[3]).toBeCloseTo(1);
});
it('ycbcr белого: y≈1, cb≈cr≈0.5', () => {
it("ycbcr белого: y≈1, cb≈cr≈0.5", () => {
const [y, cb, cr] = SPACES.ycbcr.convert({ r: 255, g: 255, b: 255 });
expect(y).toBeCloseTo(1);
expect(cb).toBeCloseTo(0.5, 2);
expect(cr).toBeCloseTo(0.5, 2);
});
it('lab белого: l≈1, a≈b≈0.5 (центр)', () => {
it("lab белого: l≈1, a≈b≈0.5 (центр)", () => {
const [l, a, bb] = SPACES.lab.convert({ r: 255, g: 255, b: 255 });
expect(l).toBeCloseTo(1, 2);
expect(a).toBeCloseTo(0.5, 2);
@@ -43,23 +43,25 @@ describe('преобразования пространств', () => {
});
});
describe('renderSpace', () => {
describe("renderSpace", () => {
const red = makeImage(1, 1, [[255, 0, 0, 255]]);
it('gray-режим: компонент y (жёлтый) чистого красного = белый', () => {
const out = renderSpace(red, 'cmyk', 'y', 'gray');
it("gray-режим: компонент y (жёлтый) чистого красного = белый", () => {
const out = renderSpace(red, "cmyk", "y", "gray");
expect([...out.data]).toEqual([255, 255, 255, 255]);
});
it('color-режим hsl красного: каналы = тон/насыщенность/светлота', () => {
const out = renderSpace(red, 'hsl', 's', 'color');
it("color-режим hsl красного: каналы = тон/насыщенность/светлота", () => {
const out = renderSpace(red, "hsl", "s", "color");
expect(out.data[0]).toBe(0);
expect(out.data[1]).toBe(255);
expect(out.data[2]).toBeGreaterThanOrEqual(127);
});
it('неизвестное пространство или компонент дают прозрачную заглушку', () => {
it("неизвестное пространство или компонент дают прозрачную заглушку", () => {
const junk = makeImage(1, 1, [[10, 20, 30, 255]]);
expect(renderSpace(junk, 'cmyk' as never, 'zz' as never, 'gray').data[3]).toBe(0);
expect(
renderSpace(junk, "cmyk" as never, "zz" as never, "gray").data[3],
).toBe(0);
});
});
+35 -19
View File
@@ -1,12 +1,12 @@
import type { PixelImage } from './types';
import { createPixelImage } from './types';
import { rgbToHsl } from './palette';
import type { Rgb } from './palette';
import type { PixelImage } from "./types";
import { createPixelImage } from "./types";
import { rgbToHsl } from "./palette";
import type { Rgb } from "./palette";
/** Все компоненты нормализованы в 0..1 в порядке объявления. */
export type SpaceComponents = number[];
export type SpaceId = 'hsl' | 'hsv' | 'hsi' | 'cmyk' | 'ycbcr' | 'lab';
export type SpaceId = "hsl" | "hsv" | "hsi" | "cmyk" | "ycbcr" | "lab";
function hueOf({ r, g, b }: Rgb): number {
const max = Math.max(r, g, b);
@@ -47,7 +47,12 @@ function rgbToCmyk({ r, g, b }: Rgb): [number, number, number, number] {
const bn = b / 255;
const k = 1 - Math.max(rn, gn, bn);
if (k === 1) return [0, 0, 0, 1];
return [(1 - rn - k) / (1 - k), (1 - gn - k) / (1 - k), (1 - bn - k) / (1 - k), k];
return [
(1 - rn - k) / (1 - k),
(1 - gn - k) / (1 - k),
(1 - bn - k) / (1 - k),
k,
];
}
function rgbToYcbcr({ r, g, b }: Rgb): [number, number, number] {
@@ -71,27 +76,34 @@ function rgbToLab({ r, g, b }: Rgb): [number, number, number] {
const fy = f(y);
const fz = f(z);
// L нормирован 0..1; a/b центрированы на 0.5 с размахом ±0.5
return [(116 * fy - 16) / 100, (500 * (fx - fy)) / 250 + 0.5, (200 * (fy - fz)) / 250 + 0.5];
return [
(116 * fy - 16) / 100,
(500 * (fx - fy)) / 250 + 0.5,
(200 * (fy - fz)) / 250 + 0.5,
];
}
type SpaceDef = { components: string[]; convert: (rgb: Rgb) => SpaceComponents };
type SpaceDef = {
components: string[];
convert: (rgb: Rgb) => SpaceComponents;
};
export const SPACES: Record<SpaceId, SpaceDef> = {
hsl: {
components: ['h', 's', 'l'],
components: ["h", "s", "l"],
convert: ({ r, g, b }) => {
const { h, s, l } = rgbToHsl({ r, g, b });
return [h / 360, s, l];
}
},
},
hsv: { components: ['h', 's', 'v'], convert: rgbToHsv },
hsi: { components: ['h', 's', 'i'], convert: rgbToHsi },
cmyk: { components: ['c', 'm', 'y', 'k'], convert: rgbToCmyk },
ycbcr: { components: ['y', 'cb', 'cr'], convert: rgbToYcbcr },
lab: { components: ['l', 'a', 'b'], convert: rgbToLab }
hsv: { components: ["h", "s", "v"], convert: rgbToHsv },
hsi: { components: ["h", "s", "i"], convert: rgbToHsi },
cmyk: { components: ["c", "m", "y", "k"], convert: rgbToCmyk },
ycbcr: { components: ["y", "cb", "cr"], convert: rgbToYcbcr },
lab: { components: ["l", "a", "b"], convert: rgbToLab },
};
export type ChannelDisplay = 'gray' | 'color';
export type ChannelDisplay = "gray" | "color";
/**
* Визуализация выбранного пространства: каждый компонент пространства
@@ -102,7 +114,7 @@ export function renderSpace(
img: PixelImage,
space: SpaceId,
component: string,
display: ChannelDisplay
display: ChannelDisplay,
): PixelImage {
const def = SPACES[space];
if (!def) return createPixelImage(img.width, img.height);
@@ -110,10 +122,14 @@ export function renderSpace(
if (idx < 0) return createPixelImage(img.width, img.height);
const out = createPixelImage(img.width, img.height);
for (let i = 0; i < img.data.length; i += 4) {
const comps = def.convert({ r: img.data[i], g: img.data[i + 1], b: img.data[i + 2] });
const comps = def.convert({
r: img.data[i],
g: img.data[i + 1],
b: img.data[i + 2],
});
const di = i;
out.data[di + 3] = img.data[i + 3];
if (display === 'gray') {
if (display === "gray") {
const v = comps[idx] * 255;
out.data[di] = v;
out.data[di + 1] = v;
+90 -80
View File
@@ -1,4 +1,4 @@
import { describe, expect, it } from 'vitest';
import { describe, expect, it } from "vitest";
import {
autoContrast,
brightnessContrast,
@@ -15,39 +15,43 @@ import {
temperature,
tint,
thresholdBlackWhite,
twoColors
} from './color';
import { makeImage } from './test-helpers';
twoColors,
} from "./color";
import { makeImage } from "./test-helpers";
describe('rgbToHex', () => {
it('форматирует базовые цвета', () => {
expect(rgbToHex(255, 0, 0)).toBe('#ff0000');
expect(rgbToHex(1, 2, 3)).toBe('#010203');
describe("rgbToHex", () => {
it("форматирует базовые цвета", () => {
expect(rgbToHex(255, 0, 0)).toBe("#ff0000");
expect(rgbToHex(1, 2, 3)).toBe("#010203");
});
it('округляет дробные значения и клампит диапазон', () => {
expect(rgbToHex(127.6, -5, 300)).toBe('#8000ff');
it("округляет дробные значения и клампит диапазон", () => {
expect(rgbToHex(127.6, -5, 300)).toBe("#8000ff");
});
});
describe('setOpacity', () => {
it('умножает альфу на процент, RGB не трогает', () => {
describe("setOpacity", () => {
it("умножает альфу на процент, RGB не трогает", () => {
const out = setOpacity(makeImage(1, 1, [[10, 20, 30, 128]]), 50);
expect([...out.data]).toEqual([10, 20, 30, 64]);
});
it('100% не меняет, 0% делает полностью прозрачным', () => {
expect(setOpacity(makeImage(1, 1, [[1, 2, 3, 200]]), 100).data[3]).toBe(200);
it("100% не меняет, 0% делает полностью прозрачным", () => {
expect(setOpacity(makeImage(1, 1, [[1, 2, 3, 200]]), 100).data[3]).toBe(
200,
);
expect(setOpacity(makeImage(1, 1, [[1, 2, 3, 200]]), 0).data[3]).toBe(0);
});
});
describe('sepia', () => {
it('применяет классическую матрицу с клампом', () => {
const out = sepia(makeImage(2, 1, [
[255, 0, 0, 255],
[255, 255, 255, 255]
]));
describe("sepia", () => {
it("применяет классическую матрицу с клампом", () => {
const out = sepia(
makeImage(2, 1, [
[255, 0, 0, 255],
[255, 255, 255, 255],
]),
);
const px = (n: number) => [...out.data.slice(n * 4, n * 4 + 4)];
expect(px(0)).toEqual([100, 89, 69, 255]);
expect(px(1)[0]).toBe(255);
@@ -55,81 +59,85 @@ describe('sepia', () => {
});
});
describe('changeHue', () => {
it('чистый красный при +120° становится чистым зелёным', () => {
describe("changeHue", () => {
it("чистый красный при +120° становится чистым зелёным", () => {
const out = changeHue(makeImage(1, 1, [[255, 0, 0, 255]]), 120);
expect([...out.data]).toEqual([0, 255, 0, 255]);
});
it('сдвиг 360° возвращает исходные цвета', () => {
it("сдвиг 360° возвращает исходные цвета", () => {
const img = makeImage(1, 1, [[90, 140, 210, 255]]);
expect([...changeHue(img, 360).data]).toEqual([...img.data]);
});
});
describe('extractChannel', () => {
it('выдаёт выбранный канал оттенками серого', () => {
const out = extractChannel(makeImage(1, 1, [[10, 20, 30, 40]]), 'green');
describe("extractChannel", () => {
it("выдаёт выбранный канал оттенками серого", () => {
const out = extractChannel(makeImage(1, 1, [[10, 20, 30, 40]]), "green");
expect([...out.data]).toEqual([20, 20, 20, 40]);
});
});
describe('swapChannels', () => {
it('переставляет каналы парами', () => {
expect([...swapChannels(makeImage(1, 1, [[10, 20, 30, 40]]), 'r-b').data]).toEqual([
30, 20, 10, 40
]);
expect([...swapChannels(makeImage(1, 1, [[10, 20, 30, 40]]), 'g-b').data]).toEqual([
10, 30, 20, 40
]);
describe("swapChannels", () => {
it("переставляет каналы парами", () => {
expect([
...swapChannels(makeImage(1, 1, [[10, 20, 30, 40]]), "r-b").data,
]).toEqual([30, 20, 10, 40]);
expect([
...swapChannels(makeImage(1, 1, [[10, 20, 30, 40]]), "g-b").data,
]).toEqual([10, 30, 20, 40]);
});
});
describe('thresholdBlackWhite', () => {
it('серый 128 относительно порога 50% — белый', () => {
expect(thresholdBlackWhite(makeImage(1, 1, [[128, 128, 128, 255]]), 50).data[0]).toBe(255);
expect(thresholdBlackWhite(makeImage(1, 1, [[128, 128, 128, 255]]), 60).data[0]).toBe(0);
describe("thresholdBlackWhite", () => {
it("серый 128 относительно порога 50% — белый", () => {
expect(
thresholdBlackWhite(makeImage(1, 1, [[128, 128, 128, 255]]), 50).data[0],
).toBe(255);
expect(
thresholdBlackWhite(makeImage(1, 1, [[128, 128, 128, 255]]), 60).data[0],
).toBe(0);
});
});
describe('posterize', () => {
it('два уровня квантуют в чёрное и белое', () => {
describe("posterize", () => {
it("два уровня квантуют в чёрное и белое", () => {
const out = posterize(
makeImage(2, 1, [
[100, 100, 100, 255],
[200, 200, 200, 255]
[200, 200, 200, 255],
]),
2
2,
);
expect(out.data[0]).toBe(0);
expect(out.data[4]).toBe(255);
});
});
describe('twoColors', () => {
it('яркие пиксели получают светлый цвет, тёмные — тёмный', () => {
describe("twoColors", () => {
it("яркие пиксели получают светлый цвет, тёмные — тёмный", () => {
const out = twoColors(
makeImage(2, 1, [
[250, 250, 250, 255],
[10, 10, 10, 128]
[10, 10, 10, 128],
]),
'#ff0000',
'#00ff00',
50
"#ff0000",
"#00ff00",
50,
);
expect([...out.data.slice(0, 4)]).toEqual([255, 0, 0, 255]);
expect([...out.data.slice(4, 8)]).toEqual([0, 255, 0, 128]);
});
});
describe('grayscale', () => {
it('считает luma по весам BT.601 с округлением', () => {
describe("grayscale", () => {
it("считает luma по весам BT.601 с округлением", () => {
const out = grayscale(
makeImage(3, 1, [
[255, 0, 0, 255],
[0, 255, 0, 255],
[0, 0, 255, 255]
])
[0, 0, 255, 255],
]),
);
const rgb = [...out.data].reduce<number[]>((acc, v, i) => {
if (i % 4 === 0) acc.push(v);
@@ -138,7 +146,7 @@ describe('grayscale', () => {
expect(rgb).toEqual([76, 150, 29]);
});
it('сохраняет альфу и не мутирует вход', () => {
it("сохраняет альфу и не мутирует вход", () => {
const img = makeImage(1, 1, [[10, 20, 30, 200]]);
const out = grayscale(img);
expect([...out.data]).toEqual([18, 18, 18, 200]);
@@ -146,89 +154,91 @@ describe('grayscale', () => {
});
});
describe('invert', () => {
it('инвертирует RGB, не трогая альфу', () => {
describe("invert", () => {
it("инвертирует RGB, не трогая альфу", () => {
const out = invert(makeImage(1, 1, [[10, 200, 30, 7]]));
expect([...out.data]).toEqual([245, 55, 225, 7]);
});
});
describe('brightnessContrast', () => {
describe("brightnessContrast", () => {
const pixel = (r: number) => makeImage(1, 1, [[r, r, r, 255]]);
const red = (out: number[]) => [out[0], out[1], out[2]];
it('b=0, c=0 — тождественное преобразование', () => {
it("b=0, c=0 — тождественное преобразование", () => {
const out = brightnessContrast(pixel(77), 0, 0);
expect(red([...out.data])).toEqual([77, 77, 77]);
});
it('brightness +100 насыщает всё в белый', () => {
it("brightness +100 насыщает всё в белый", () => {
const out = brightnessContrast(pixel(10), 100, 0);
expect(red([...out.data])).toEqual([255, 255, 255]);
});
it('brightness -100 заливает чёрным', () => {
it("brightness -100 заливает чёрным", () => {
const out = brightnessContrast(pixel(240), -100, 0);
expect(red([...out.data])).toEqual([0, 0, 0]);
});
it('contrast -100 сводит всё к серому 128', () => {
it("contrast -100 сводит всё к серому 128", () => {
const out = brightnessContrast(pixel(30), 0, -100);
expect(red([...out.data])).toEqual([128, 128, 128]);
});
it('параметры вне диапазона клампятся', () => {
it("параметры вне диапазона клампятся", () => {
const out = brightnessContrast(pixel(10), 150, 0);
expect(red([...out.data])).toEqual([255, 255, 255]);
});
it('альфа не меняется', () => {
it("альфа не меняется", () => {
const out = brightnessContrast(makeImage(1, 1, [[10, 20, 30, 64]]), 50, 50);
expect(out.data[3]).toBe(64);
});
});
describe('gammaCorrection', () => {
it('гамма 1 — идентичность', () => {
describe("gammaCorrection", () => {
it("гамма 1 — идентичность", () => {
const img = makeImage(1, 1, [[64, 128, 192, 255]]);
expect([...gammaCorrection(img, 1).data]).toEqual([64, 128, 192, 255]);
});
it('гамма 2 удваивает яркость (64 → 128)', () => {
it("гамма 2 удваивает яркость (64 → 128)", () => {
const out = gammaCorrection(makeImage(1, 1, [[64, 64, 64, 255]]), 2);
expect(out.data[0]).toBe(128);
});
});
describe('autoContrast', () => {
it('растягивает диапазон [10..200] до [0..255]', () => {
const out = autoContrast(makeImage(2, 1, [
[10, 10, 10, 255],
[200, 200, 200, 255]
]));
describe("autoContrast", () => {
it("растягивает диапазон [10..200] до [0..255]", () => {
const out = autoContrast(
makeImage(2, 1, [
[10, 10, 10, 255],
[200, 200, 200, 255],
]),
);
expect(out.data[0]).toBe(0);
expect(out.data[4]).toBe(255);
});
});
describe('temperature', () => {
it('положительная — теплее (красный ↑, синий ↓)', () => {
describe("temperature", () => {
it("положительная — теплее (красный ↑, синий ↓)", () => {
const out = temperature(makeImage(1, 1, [[128, 128, 128, 255]]), 50);
expect(out.data[0]).toBeGreaterThan(128);
expect(out.data[2]).toBeLessThan(128);
});
it('нулевая температура не меняет', () => {
it("нулевая температура не меняет", () => {
const img = makeImage(1, 1, [[128, 128, 128, 255]]);
expect([...temperature(img, 0).data]).toEqual([...img.data]);
});
});
describe('tint', () => {
it('сила 100 на белом даёт чистый цвет', () => {
const out = tint(makeImage(1, 1, [[255, 255, 255, 255]]), '#ff0000', 100);
describe("tint", () => {
it("сила 100 на белом даёт чистый цвет", () => {
const out = tint(makeImage(1, 1, [[255, 255, 255, 255]]), "#ff0000", 100);
expect([...out.data]).toEqual([255, 0, 0, 255]);
});
it('сила 0 — идентичность', () => {
it("сила 0 — идентичность", () => {
const img = makeImage(1, 1, [[100, 150, 200, 255]]);
expect([...tint(img, '#ff0000', 0).data]).toEqual([...img.data]);
expect([...tint(img, "#ff0000", 0).data]).toEqual([...img.data]);
});
});
});
+36 -21
View File
@@ -1,9 +1,9 @@
import { clonePixelImage, createPixelImage, type PixelImage } from './types';
import { ToolError } from './errors';
import { clonePixelImage, createPixelImage, type PixelImage } from "./types";
import { ToolError } from "./errors";
export type RgbChannel = 'red' | 'green' | 'blue';
export type RgbChannel = "red" | "green" | "blue";
export type ChannelSwapPair = 'r-g' | 'r-b' | 'g-b';
export type ChannelSwapPair = "r-g" | "r-b" | "g-b";
export function setOpacity(img: PixelImage, percent: number): PixelImage {
const factor = clamp(percent, 0, 100) / 100;
@@ -74,7 +74,10 @@ function hueComponent(p: number, q: number, t: number): number {
const CHANNEL_INDEX: Record<RgbChannel, number> = { red: 0, green: 1, blue: 2 };
export function extractChannel(img: PixelImage, channel: RgbChannel): PixelImage {
export function extractChannel(
img: PixelImage,
channel: RgbChannel,
): PixelImage {
const index = CHANNEL_INDEX[channel];
const out = createPixelImage(img.width, img.height);
for (let i = 0; i < out.data.length; i += 4) {
@@ -88,12 +91,15 @@ export function extractChannel(img: PixelImage, channel: RgbChannel): PixelImage
}
const SWAP_INDEX: Record<ChannelSwapPair, [number, number]> = {
'r-g': [0, 1],
'r-b': [0, 2],
'g-b': [1, 2]
"r-g": [0, 1],
"r-b": [0, 2],
"g-b": [1, 2],
};
export function swapChannels(img: PixelImage, pair: ChannelSwapPair): PixelImage {
export function swapChannels(
img: PixelImage,
pair: ChannelSwapPair,
): PixelImage {
const [a, b] = SWAP_INDEX[pair];
const out = createPixelImage(img.width, img.height);
for (let i = 0; i < out.data.length; i += 4) {
@@ -108,11 +114,15 @@ export function swapChannels(img: PixelImage, pair: ChannelSwapPair): PixelImage
return out;
}
export function thresholdBlackWhite(img: PixelImage, thresholdPercent: number): PixelImage {
export function thresholdBlackWhite(
img: PixelImage,
thresholdPercent: number,
): PixelImage {
const threshold = (clamp(thresholdPercent, 0, 100) / 100) * 255;
const out = createPixelImage(img.width, img.height);
for (let i = 0; i < out.data.length; i += 4) {
const luma = 0.299 * img.data[i] + 0.587 * img.data[i + 1] + 0.114 * img.data[i + 2];
const luma =
0.299 * img.data[i] + 0.587 * img.data[i + 1] + 0.114 * img.data[i + 2];
const v = luma >= threshold ? 255 : 0;
out.data[i] = v;
out.data[i + 1] = v;
@@ -128,7 +138,9 @@ export function posterize(img: PixelImage, levels: number): PixelImage {
const out = createPixelImage(img.width, img.height);
for (let i = 0; i < out.data.length; i += 4) {
for (let ch = 0; ch < 3; ch++) {
out.data[i + ch] = Math.round(Math.round(img.data[i + ch] / stepSize) * stepSize);
out.data[i + ch] = Math.round(
Math.round(img.data[i + ch] / stepSize) * stepSize,
);
}
out.data[i + 3] = img.data[i + 3];
}
@@ -139,14 +151,15 @@ export function twoColors(
img: PixelImage,
lightHex: string,
darkHex: string,
thresholdPercent: number
thresholdPercent: number,
): PixelImage {
const [lr, lg, lb] = parseColor(lightHex);
const [dr, dg, db] = parseColor(darkHex);
const threshold = (clamp(thresholdPercent, 0, 100) / 100) * 255;
const out = createPixelImage(img.width, img.height);
for (let i = 0; i < out.data.length; i += 4) {
const luma = 0.299 * img.data[i] + 0.587 * img.data[i + 1] + 0.114 * img.data[i + 2];
const luma =
0.299 * img.data[i] + 0.587 * img.data[i + 1] + 0.114 * img.data[i + 2];
if (luma >= threshold) {
out.data[i] = lr;
out.data[i + 1] = lg;
@@ -164,20 +177,21 @@ export function twoColors(
function parseColor(hex: string): [number, number, number] {
const match = /^#([0-9a-f]{6})$/i.exec(hex.trim());
if (!match) {
throw new ToolError('errors.badHex', { value: hex });
throw new ToolError("errors.badHex", { value: hex });
}
const digits = match[1];
return [
parseInt(digits.slice(0, 2), 16),
parseInt(digits.slice(2, 4), 16),
parseInt(digits.slice(4, 6), 16)
parseInt(digits.slice(4, 6), 16),
];
}
export function grayscale(img: PixelImage): PixelImage {
const out = createPixelImage(img.width, img.height);
for (let i = 0; i < img.data.length; i += 4) {
const luma = 0.299 * img.data[i] + 0.587 * img.data[i + 1] + 0.114 * img.data[i + 2];
const luma =
0.299 * img.data[i] + 0.587 * img.data[i + 1] + 0.114 * img.data[i + 2];
out.data[i] = luma;
out.data[i + 1] = luma;
out.data[i + 2] = luma;
@@ -200,7 +214,7 @@ export function invert(img: PixelImage): PixelImage {
export function brightnessContrast(
img: PixelImage,
brightness: number,
contrast: number
contrast: number,
): PixelImage {
const offset = (clamp(brightness, -100, 100) / 100) * 255;
const c = (clamp(contrast, -100, 100) / 100) * 255;
@@ -217,7 +231,8 @@ export function brightnessContrast(
}
export function rgbToHex(r: number, g: number, b: number): string {
const byte = (v: number) => clamp(Math.round(v), 0, 255).toString(16).padStart(2, '0');
const byte = (v: number) =>
clamp(Math.round(v), 0, 255).toString(16).padStart(2, "0");
return `#${byte(r)}${byte(g)}${byte(b)}`;
}
@@ -286,11 +301,11 @@ export function temperature(img: PixelImage, percent: number): PixelImage {
export function tint(
img: PixelImage,
colorHex: string,
strengthPercent: number
strengthPercent: number,
): PixelImage {
const s = clamp(strengthPercent, 0, 100) / 100;
const match = /^#([0-9a-f]{6})$/i.exec(colorHex.trim());
if (!match) throw new ToolError('errors.badHex', { value: colorHex });
if (!match) throw new ToolError("errors.badHex", { value: colorHex });
const d = match[1];
const tr = parseInt(d.slice(0, 2), 16) / 255;
const tg = parseInt(d.slice(2, 4), 16) / 255;
+11 -10
View File
@@ -1,34 +1,35 @@
import { describe, expect, it } from 'vitest';
import { COMPRESSION_LEVELS, findMaxColorsWithin } from './compress';
import { describe, expect, it } from "vitest";
import { COMPRESSION_LEVELS, findMaxColorsWithin } from "./compress";
describe('COMPRESSION_LEVELS', () => {
it('пресеты упорядочены по убыванию цветов', () => {
describe("COMPRESSION_LEVELS", () => {
it("пресеты упорядочены по убыванию цветов", () => {
const values = Object.values(COMPRESSION_LEVELS);
for (let i = 1; i < values.length; i++) expect(values[i - 1]).toBeGreaterThan(values[i]);
for (let i = 1; i < values.length; i++)
expect(values[i - 1]).toBeGreaterThan(values[i]);
});
});
describe('findMaxColorsWithin', () => {
describe("findMaxColorsWithin", () => {
const sizeOf = (k: number) => 1000 + k * 100; // размер растёт с k
it('подбирает максимум k, укладывающийся в цель', async () => {
it("подбирает максимум k, укладывающийся в цель", async () => {
// target 5200 → подходит k≤42 → ожидаем 42 при maxK≥42
const k = await findMaxColorsWithin(5200, 256, async (kk) => sizeOf(kk));
expect(k).toBeGreaterThanOrEqual(40);
expect(sizeOf(k)).toBeLessThanOrEqual(5200);
});
it('цель достигается даже на минимуме — возвращает 2', async () => {
it("цель достигается даже на минимуме — возвращает 2", async () => {
const k = await findMaxColorsWithin(50, 256, async (kk) => sizeOf(kk));
expect(k).toBe(2);
});
it('encodeSize null трактуется как провал', async () => {
it("encodeSize null трактуется как провал", async () => {
const k = await findMaxColorsWithin(999999, 16, async () => null);
expect(k).toBe(2);
});
it('бинарный поиск сходится быстрее полного перебора', async () => {
it("бинарный поиск сходится быстрее полного перебора", async () => {
let calls = 0;
await findMaxColorsWithin(30000, 256, async (kk) => {
calls++;
+2 -2
View File
@@ -3,7 +3,7 @@ export const COMPRESSION_LEVELS = {
light: 192,
balanced: 96,
strong: 44,
extreme: 16
extreme: 16,
} as const;
export type CompressionLevel = keyof typeof COMPRESSION_LEVELS;
@@ -16,7 +16,7 @@ export type CompressionLevel = keyof typeof COMPRESSION_LEVELS;
export async function findMaxColorsWithin(
targetBytes: number,
maxK: number,
encodeSize: (k: number) => Promise<number | null>
encodeSize: (k: number) => Promise<number | null>,
): Promise<number> {
const hi = Math.max(2, Math.round(maxK));
let ok = 2;
+34 -30
View File
@@ -1,19 +1,19 @@
import { describe, expect, it } from 'vitest';
import { convolve, gaussianBlur, sharpen } from './convolution';
import { makeImage } from './test-helpers';
import { describe, expect, it } from "vitest";
import { convolve, gaussianBlur, sharpen } from "./convolution";
import { makeImage } from "./test-helpers";
const SHARPEN_KERNEL = [0, -1, 0, -1, 5, -1, 0, -1, 0];
describe('convolve', () => {
it('крестовое ядро резкости на полоске из трёх пикселей', () => {
describe("convolve", () => {
it("крестовое ядро резкости на полоске из трёх пикселей", () => {
const out = convolve(
makeImage(3, 1, [
[0, 0, 0, 255],
[100, 100, 100, 255],
[0, 0, 0, 255]
[0, 0, 0, 255],
]),
SHARPEN_KERNEL,
3
3,
);
expect([...out.data.slice(4, 8)]).toEqual([255, 255, 255, 255]);
expect([...out.data.slice(0, 4)]).toEqual([0, 0, 0, 255]);
@@ -23,39 +23,41 @@ describe('convolve', () => {
it.each([
[2, 3],
[3.5, 3],
[0, 3]
])('бросает ошибку на некорректном размере ядра %i', (size) => {
expect(() => convolve(makeImage(1, 1, [[0, 0, 0, 255]]), [1], size as number)).toThrow();
[0, 3],
])("бросает ошибку на некорректном размере ядра %i", (size) => {
expect(() =>
convolve(makeImage(1, 1, [[0, 0, 0, 255]]), [1], size as number),
).toThrow();
});
});
describe('sharpen', () => {
it('сила 0 возвращает копию', () => {
describe("sharpen", () => {
it("сила 0 возвращает копию", () => {
const img = makeImage(2, 2, [
[10, 20, 30, 255],
[40, 50, 60, 128],
[70, 80, 90, 255],
[100, 110, 120, 200]
[100, 110, 120, 200],
]);
expect([...sharpen(img, 0).data]).toEqual([...img.data]);
});
it('сила 100 применяет чистое ядро резкости', () => {
it("сила 100 применяет чистое ядро резкости", () => {
const out = sharpen(
makeImage(3, 1, [
[0, 0, 0, 255],
[100, 100, 100, 255],
[0, 0, 0, 255]
[0, 0, 0, 255],
]),
100
100,
);
expect(out.data[4]).toBe(255);
expect(out.data[0]).toBe(0);
});
});
describe('gaussianBlur', () => {
it('постоянное изображение не меняется ни в RGB, ни в альфе', () => {
describe("gaussianBlur", () => {
it("постоянное изображение не меняется ни в RGB, ни в альфе", () => {
const img = makeImage(3, 3, new Array(9).fill([40, 80, 120, 128]));
const out = gaussianBlur(img, 16);
for (let i = 0; i < out.data.length; i++) {
@@ -63,13 +65,15 @@ describe('gaussianBlur', () => {
}
});
it('далёкие углы остаются прозрачными, цвет центра не искажается', () => {
it("далёкие углы остаются прозрачными, цвет центра не искажается", () => {
const size = 61;
const pixels: number[][] = [];
for (let y = 0; y < size; y++) {
for (let x = 0; x < size; x++) {
pixels.push(
x >= 26 && x <= 34 && y >= 26 && y <= 34 ? [200, 50, 25, 255] : [0, 0, 0, 0]
x >= 26 && x <= 34 && y >= 26 && y <= 34
? [200, 50, 25, 255]
: [0, 0, 0, 0],
);
}
}
@@ -85,50 +89,50 @@ describe('gaussianBlur', () => {
expect(out.data[center + 2]).toBe(25);
});
it('симметричный вход даёт симметричный результат', () => {
it("симметричный вход даёт симметричный результат", () => {
const leftByRow = [
[
[255, 0, 0, 255],
[10, 20, 30, 255],
[64, 64, 64, 64],
[5, 5, 5, 200]
[5, 5, 5, 200],
],
[
[10, 20, 30, 255],
[200, 100, 50, 255],
[1, 2, 3, 4],
[90, 90, 90, 250]
[90, 90, 90, 250],
],
[
[64, 64, 64, 64],
[1, 2, 3, 4],
[128, 128, 128, 128],
[40, 40, 40, 240]
[40, 40, 40, 240],
],
[
[200, 100, 50, 255],
[90, 90, 90, 250],
[40, 40, 40, 240],
[7, 7, 7, 255]
[7, 7, 7, 255],
],
[
[10, 20, 30, 255],
[1, 2, 3, 4],
[64, 64, 64, 64],
[90, 90, 90, 250]
[90, 90, 90, 250],
],
[
[64, 64, 64, 64],
[200, 100, 50, 255],
[5, 5, 5, 200],
[1, 2, 3, 4]
[1, 2, 3, 4],
],
[
[5, 5, 5, 200],
[40, 40, 40, 240],
[90, 90, 90, 250],
[128, 128, 128, 128]
]
[128, 128, 128, 128],
],
];
const pixels: number[][] = [];
for (let y = 0; y < 7; y++) {
@@ -146,7 +150,7 @@ describe('gaussianBlur', () => {
blurred.data[ri],
blurred.data[ri + 1],
blurred.data[ri + 2],
blurred.data[ri + 3]
blurred.data[ri + 3],
]);
}
}
+20 -11
View File
@@ -1,18 +1,18 @@
import { clonePixelImage, createPixelImage, type PixelImage } from './types';
import { ToolError } from './errors';
import { clonePixelImage, createPixelImage, type PixelImage } from "./types";
import { ToolError } from "./errors";
type Plane = Float64Array;
export function convolve(
img: PixelImage,
kernel: readonly number[],
size: number
size: number,
): PixelImage {
if (!Number.isInteger(size) || size < 1 || size % 2 === 0) {
throw new ToolError('errors.radiusInt');
throw new ToolError("errors.radiusInt");
}
if (kernel.length !== size * size) {
throw new ToolError('errors.kernelSize');
throw new ToolError("errors.kernelSize");
}
const half = Math.floor(size / 2);
const out = createPixelImage(img.width, img.height);
@@ -24,12 +24,14 @@ export function convolve(
const sy = clampInt(y + ky - half, 0, img.height - 1);
for (let kx = 0; kx < size; kx++) {
const sx = clampInt(x + kx - half, 0, img.width - 1);
acc += img.data[(sy * img.width + sx) * 4 + ch] * kernel[ky * size + kx];
acc +=
img.data[(sy * img.width + sx) * 4 + ch] * kernel[ky * size + kx];
}
}
out.data[(y * out.width + x) * 4 + ch] = acc;
}
out.data[(y * out.width + x) * 4 + 3] = img.data[(y * img.width + x) * 4 + 3];
out.data[(y * out.width + x) * 4 + 3] =
img.data[(y * img.width + x) * 4 + 3];
}
}
return out;
@@ -103,7 +105,13 @@ export function gaussianBlur(img: PixelImage, radiusPx: number): PixelImage {
return out;
}
function blurPlanePass(plane: Plane, tmp: Plane, w: number, h: number, r: number): void {
function blurPlanePass(
plane: Plane,
tmp: Plane,
w: number,
h: number,
r: number,
): void {
blurPlaneHorizontal(plane, tmp, w, h, r);
blurPlaneVertical(tmp, plane, w, h, r);
}
@@ -113,7 +121,7 @@ function blurPlaneHorizontal(
dst: Plane,
w: number,
h: number,
r: number
r: number,
): void {
const div = 2 * r + 1;
const inv = 1 / div;
@@ -137,7 +145,7 @@ function blurPlaneVertical(
dst: Plane,
w: number,
h: number,
r: number
r: number,
): void {
const div = 2 * r + 1;
const inv = 1 / div;
@@ -160,7 +168,8 @@ function boxesForGauss(sigma: number, boxes: number): number[] {
let wl = Math.floor(wIdeal);
if (wl % 2 === 0) wl--;
const wu = wl + 2;
const mIdeal = (12 * sigma * sigma - boxes * wl * wl - boxes * wl - boxes) / (4 * wl + 4);
const mIdeal =
(12 * sigma * sigma - boxes * wl * wl - boxes * wl - boxes) / (4 * wl + 4);
const m = Math.round(mIdeal);
const sizes: number[] = [];
for (let i = 0; i < boxes; i++) {
+10 -10
View File
@@ -1,19 +1,19 @@
import { describe, expect, it } from 'vitest';
import { formatStamp } from './datefmt';
import { describe, expect, it } from "vitest";
import { formatStamp } from "./datefmt";
const d = new Date(2026, 7, 25, 9, 5, 3);
describe('formatStamp', () => {
it('разворачивает все базовые токены', () => {
expect(formatStamp(d, 'YYYY-MM-DD hh:mm:ss')).toBe('2026-08-25 09:05:03');
describe("formatStamp", () => {
it("разворачивает все базовые токены", () => {
expect(formatStamp(d, "YYYY-MM-DD hh:mm:ss")).toBe("2026-08-25 09:05:03");
});
it('произвольный текст между токенами сохраняется', () => {
expect(formatStamp(d, 'DD.MM.YYYY')).toBe('25.08.2026');
expect(formatStamp(d, 'YYYY год, MM месяц')).toBe('2026 год, 08 месяц');
it("произвольный текст между токенами сохраняется", () => {
expect(formatStamp(d, "DD.MM.YYYY")).toBe("25.08.2026");
expect(formatStamp(d, "YYYY год, MM месяц")).toBe("2026 год, 08 месяц");
});
it('неизвестные последовательности не трогаются', () => {
expect(formatStamp(d, 'YYYYYY MMМ')).toBe('2026YY 08М');
it("неизвестные последовательности не трогаются", () => {
expect(formatStamp(d, "YYYYYY MMМ")).toBe("2026YY 08М");
});
});
+7 -7
View File
@@ -1,4 +1,4 @@
const PAD2 = (n: number) => String(n).padStart(2, '0');
const PAD2 = (n: number) => String(n).padStart(2, "0");
/**
* Мини-форматтер штампа даты: токены YYYY MM DD hh mm ss заменяются
@@ -7,17 +7,17 @@ const PAD2 = (n: number) => String(n).padStart(2, '0');
export function formatStamp(date: Date, pattern: string): string {
return pattern.replace(/YYYY|MM|DD|hh|mm|ss/g, (token) => {
switch (token) {
case 'YYYY':
case "YYYY":
return String(date.getFullYear());
case 'MM':
case "MM":
return PAD2(date.getMonth() + 1);
case 'DD':
case "DD":
return PAD2(date.getDate());
case 'hh':
case "hh":
return PAD2(date.getHours());
case 'mm':
case "mm":
return PAD2(date.getMinutes());
case 'ss':
case "ss":
return PAD2(date.getSeconds());
default:
return token;
+94 -33
View File
@@ -1,33 +1,44 @@
import { ToolError } from './errors';
import type { PixelImage } from './types';
import { anchorOrigin, tileGrid, wrapText, type Position9 } from './textdraw';
import { ToolError } from "./errors";
import type { PixelImage } from "./types";
import { anchorOrigin, tileGrid, wrapText, type Position9 } from "./textdraw";
export type TextFont = 'sans' | 'serif' | 'mono';
export type TextFont = "sans" | "serif" | "mono";
const FONT_STACKS: Record<TextFont, string> = {
sans: 'system-ui, -apple-system, "Segoe UI", Roboto, sans-serif',
serif: 'Georgia, "Times New Roman", serif',
mono: 'ui-monospace, "Cascadia Code", Consolas, monospace'
mono: 'ui-monospace, "Cascadia Code", Consolas, monospace',
};
function ctx2d(w: number, h: number): { canvas: HTMLCanvasElement; ctx: CanvasRenderingContext2D } {
const canvas = document.createElement('canvas');
function ctx2d(
w: number,
h: number,
): { canvas: HTMLCanvasElement; ctx: CanvasRenderingContext2D } {
const canvas = document.createElement("canvas");
canvas.width = w;
canvas.height = h;
const ctx = canvas.getContext('2d', { willReadFrequently: true });
if (!ctx) throw new ToolError('errors.noCanvasCtx');
const ctx = canvas.getContext("2d", { willReadFrequently: true });
if (!ctx) throw new ToolError("errors.noCanvasCtx");
return { canvas, ctx };
}
function toPixelImage(canvas: HTMLCanvasElement): PixelImage {
const ctx = canvas.getContext('2d');
if (!ctx) throw new ToolError('errors.noCanvasCtx');
const ctx = canvas.getContext("2d");
if (!ctx) throw new ToolError("errors.noCanvasCtx");
const imageData = ctx.getImageData(0, 0, canvas.width, canvas.height);
return { width: imageData.width, height: imageData.height, data: imageData.data };
return {
width: imageData.width,
height: imageData.height,
data: imageData.data,
};
}
export function fontString(size: number, font: TextFont, bold: boolean): string {
return `${bold ? '700 ' : '400 '}${size}px ${FONT_STACKS[font]}`;
export function fontString(
size: number,
font: TextFont,
bold: boolean,
): string {
return `${bold ? "700 " : "400 "}${size}px ${FONT_STACKS[font]}`;
}
export interface TextBlockOptions {
@@ -46,9 +57,16 @@ export interface TextBlockOptions {
}
/** Одна надпись (с автопереносом и опциональной плашкой) поверх изображения. */
export function drawTextBlock(img: PixelImage, o: TextBlockOptions): PixelImage {
export function drawTextBlock(
img: PixelImage,
o: TextBlockOptions,
): PixelImage {
const { canvas, ctx } = ctx2d(img.width, img.height);
ctx.putImageData(new ImageData(new Uint8ClampedArray(img.data), img.width, img.height), 0, 0);
ctx.putImageData(
new ImageData(new Uint8ClampedArray(img.data), img.width, img.height),
0,
0,
);
ctx.font = fontString(o.fontSize, o.font, o.bold);
const maxWidth = ((o.maxWidthPercent ?? 90) / 100) * img.width;
@@ -57,11 +75,18 @@ export function drawTextBlock(img: PixelImage, o: TextBlockOptions): PixelImage
const ascent = o.fontSize * 0.8;
const blockW = Math.min(
maxWidth,
lines.reduce((max, s) => Math.max(max, ctx.measureText(s).width), 0)
lines.reduce((max, s) => Math.max(max, ctx.measureText(s).width), 0),
);
const blockH = lines.length * lineH;
const origin = anchorOrigin(o.position, blockW, blockH, img.width, img.height, o.margin);
const origin = anchorOrigin(
o.position,
blockW,
blockH,
img.width,
img.height,
o.margin,
);
ctx.save();
ctx.globalAlpha = o.opacityPercent / 100;
@@ -77,7 +102,7 @@ export function drawTextBlock(img: PixelImage, o: TextBlockOptions): PixelImage
ctx.globalAlpha = o.opacityPercent / 100;
}
ctx.fillStyle = o.color;
ctx.textBaseline = 'alphabetic';
ctx.textBaseline = "alphabetic";
lines.forEach((line, i) => {
ctx.fillText(line, origin.x, origin.y + ascent + i * lineH);
});
@@ -86,7 +111,10 @@ export function drawTextBlock(img: PixelImage, o: TextBlockOptions): PixelImage
return toPixelImage(canvas);
}
export interface TileTextOptions extends Omit<TextBlockOptions, 'position' | 'margin' | 'angleDeg'> {
export interface TileTextOptions extends Omit<
TextBlockOptions,
"position" | "margin" | "angleDeg"
> {
stepX: number;
stepY: number;
angleDeg: number;
@@ -110,7 +138,10 @@ export function renderTextToImage(o: TextToImageOptions): PixelImage {
measure.font = fontString(o.fontSize, o.font, o.bold);
const maxWidth = o.maxTextWidth ?? 4000;
const lines = [o.text];
const textW = Math.min(maxWidth, Math.max(measure.measureText(o.text).width, 1));
const textW = Math.min(
maxWidth,
Math.max(measure.measureText(o.text).width, 1),
);
const lineH = o.fontSize * 1.25;
const w = Math.max(1, Math.ceil(textW + o.padding * 2));
@@ -123,7 +154,7 @@ export function renderTextToImage(o: TextToImageOptions): PixelImage {
}
ctx.font = fontString(o.fontSize, o.font, o.bold);
ctx.fillStyle = o.color;
ctx.textBaseline = 'top';
ctx.textBaseline = "top";
lines.forEach((line) => ctx.fillText(line, o.padding, o.padding));
return toPixelImage(canvas);
}
@@ -132,8 +163,8 @@ export function renderTextToImage(o: TextToImageOptions): PixelImage {
export function renderEmoji(symbol: string, size: number): PixelImage {
const { canvas, ctx } = ctx2d(size, size);
ctx.font = `${Math.round(size * 0.72)}px "Apple Color Emoji","Segoe UI Emoji","Noto Color Emoji",sans-serif`;
ctx.textAlign = 'center';
ctx.textBaseline = 'middle';
ctx.textAlign = "center";
ctx.textBaseline = "middle";
ctx.fillText(symbol, size / 2, size / 2 + size * 0.04);
return toPixelImage(canvas);
}
@@ -147,19 +178,37 @@ export interface ImageWatermarkOptions {
}
/** Картинка-знак поверх изображения: масштаб от ширины холста, позиция 3×3. */
export function drawImageWatermark(img: PixelImage, o: ImageWatermarkOptions): PixelImage {
export function drawImageWatermark(
img: PixelImage,
o: ImageWatermarkOptions,
): PixelImage {
const { canvas, ctx } = ctx2d(img.width, img.height);
ctx.putImageData(new ImageData(new Uint8ClampedArray(img.data), img.width, img.height), 0, 0);
ctx.putImageData(
new ImageData(new Uint8ClampedArray(img.data), img.width, img.height),
0,
0,
);
const w = Math.max(1, Math.round((img.width * o.scalePercent) / 100));
const h = Math.max(1, Math.round((w * o.mark.height) / o.mark.width));
const origin = anchorOrigin(o.position, w, h, img.width, img.height, o.margin);
const origin = anchorOrigin(
o.position,
w,
h,
img.width,
img.height,
o.margin,
);
const markCanvas = ctx2d(o.mark.width, o.mark.height);
markCanvas.ctx.putImageData(
new ImageData(new Uint8ClampedArray(o.mark.data), o.mark.width, o.mark.height),
new ImageData(
new Uint8ClampedArray(o.mark.data),
o.mark.width,
o.mark.height,
),
0,
0,
0
);
ctx.save();
@@ -173,21 +222,33 @@ export function drawImageWatermark(img: PixelImage, o: ImageWatermarkOptions): P
/** Повторяющаяся диагональная плитка текста на весь холст. */
export function drawTextTile(img: PixelImage, o: TileTextOptions): PixelImage {
const { canvas, ctx } = ctx2d(img.width, img.height);
ctx.putImageData(new ImageData(new Uint8ClampedArray(img.data), img.width, img.height), 0, 0);
ctx.putImageData(
new ImageData(new Uint8ClampedArray(img.data), img.width, img.height),
0,
0,
);
ctx.font = fontString(o.fontSize, o.font, o.bold);
const sample = o.text.length > 0 ? o.text : ' ';
const sample = o.text.length > 0 ? o.text : " ";
const blockW = ctx.measureText(sample).width;
const blockH = o.fontSize * 1.4;
const points = tileGrid(img.width, img.height, o.angleDeg, o.stepX, o.stepY, blockW, blockH);
const points = tileGrid(
img.width,
img.height,
o.angleDeg,
o.stepX,
o.stepY,
blockW,
blockH,
);
ctx.save();
ctx.translate(img.width / 2, img.height / 2);
ctx.rotate((o.angleDeg * Math.PI) / 180);
ctx.globalAlpha = o.opacityPercent / 100;
ctx.fillStyle = o.color;
ctx.textBaseline = 'middle';
ctx.textBaseline = "middle";
for (const p of points) {
ctx.fillText(sample, p.x - blockW / 2, p.y);
}
+6 -6
View File
@@ -1,14 +1,14 @@
import { describe, expect, it } from 'vitest';
import { vignette } from './effects';
import { makeImage } from './test-helpers';
import { describe, expect, it } from "vitest";
import { vignette } from "./effects";
import { makeImage } from "./test-helpers";
describe('vignette', () => {
it('сила 0 — идентичное преобразование', () => {
describe("vignette", () => {
it("сила 0 — идентичное преобразование", () => {
const img = makeImage(3, 3, new Array(9).fill([200, 100, 50, 255]));
expect([...vignette(img, 0).data]).toEqual([...img.data]);
});
it('углы темнее центра', () => {
it("углы темнее центра", () => {
const img = makeImage(7, 7, new Array(49).fill([200, 200, 200, 255]));
const out = vignette(img, 80);
const centerR = out.data[(3 * 7 + 3) * 4];
+1 -1
View File
@@ -1,4 +1,4 @@
import { clonePixelImage, createPixelImage, type PixelImage } from './types';
import { clonePixelImage, createPixelImage, type PixelImage } from "./types";
export function vignette(img: PixelImage, strengthPercent: number): PixelImage {
const strength = Math.min(Math.max(strengthPercent, 0), 100) / 100;
+1 -1
View File
@@ -11,7 +11,7 @@ export class ToolError extends Error {
constructor(key: string, vars?: ErrorVars) {
super(key);
this.name = 'ToolError';
this.name = "ToolError";
this.key = key;
this.vars = vars;
}
+30 -30
View File
@@ -1,4 +1,4 @@
import { describe, expect, it } from 'vitest';
import { describe, expect, it } from "vitest";
import {
changeCanvasSize,
contentBounds,
@@ -6,9 +6,9 @@ import {
forceOrientation,
padToRatio,
symmetricCopy,
trimToContent
} from './geometry';
import { makeImage } from './test-helpers';
trimToContent,
} from "./geometry";
import { makeImage } from "./test-helpers";
const bordered = () => {
// 4×4: рамка из прозрачных пикселей вокруг красного центра 2×2
@@ -23,12 +23,12 @@ const bordered = () => {
return img;
};
describe('contentBounds / trimToContent', () => {
it('границы по порогу альфы', () => {
describe("contentBounds / trimToContent", () => {
it("границы по порогу альфы", () => {
expect(contentBounds(bordered(), 0)).toEqual({ x: 1, y: 1, w: 2, h: 2 });
});
it('trim обрезает поля и сохраняет содержимое', () => {
it("trim обрезает поля и сохраняет содержимое", () => {
const out = trimToContent(bordered(), 0);
expect(out.width).toBe(2);
expect(out.height).toBe(2);
@@ -36,7 +36,7 @@ describe('contentBounds / trimToContent', () => {
expect(out.data[3]).toBe(255);
});
it('полностью прозрачное изображение → 1×1', () => {
it("полностью прозрачное изображение → 1×1", () => {
const empty = makeImage(3, 3, new Array(9).fill([0, 0, 0, 0]));
const out = trimToContent(empty, 0);
expect(out.width).toBe(1);
@@ -44,43 +44,43 @@ describe('contentBounds / trimToContent', () => {
});
});
describe('changeCanvasSize', () => {
describe("changeCanvasSize", () => {
const img = makeImage(2, 2, [
[1, 1, 1, 255],
[2, 2, 2, 255],
[3, 3, 3, 255],
[4, 4, 4, 255]
[4, 4, 4, 255],
]);
it('увеличение с якорем center — прозрачные поля со всех сторон', () => {
const out = changeCanvasSize(img, 4, 4, 'center');
it("увеличение с якорем center — прозрачные поля со всех сторон", () => {
const out = changeCanvasSize(img, 4, 4, "center");
expect(out.width).toBe(4);
expect(out.data[3]).toBe(0);
expect(out.data[(1 * 4 + 1) * 4 + 3]).toBe(255);
});
it('увеличение с якорем top-left — контент прижат в угол', () => {
const out = changeCanvasSize(img, 4, 4, 'top-left');
it("увеличение с якорем top-left — контент прижат в угол", () => {
const out = changeCanvasSize(img, 4, 4, "top-left");
expect(out.data[3]).toBe(255);
expect(out.data[(3 * 4 + 3) * 4 + 3]).toBe(0);
});
it('уменьшение обрезает как кроп от якоря bottom-right', () => {
const out = changeCanvasSize(img, 1, 1, 'bottom-right');
it("уменьшение обрезает как кроп от якоря bottom-right", () => {
const out = changeCanvasSize(img, 1, 1, "bottom-right");
expect(out.data[0]).toBe(4);
});
});
describe('соотношение сторон', () => {
describe("соотношение сторон", () => {
const wide = makeImage(400, 200, new Array(80000).fill([9, 9, 9, 255]));
it('cropToRatio 1:1 из 2:1 → квадрат по высоте', () => {
it("cropToRatio 1:1 из 2:1 → квадрат по высоте", () => {
const out = cropToRatio(wide, 1);
expect(out.width).toBe(200);
expect(out.height).toBe(200);
});
it('padToRatio 1:1 из 2:1 → квадрат с прозрачными полями', () => {
it("padToRatio 1:1 из 2:1 → квадрат с прозрачными полями", () => {
const out = padToRatio(wide, 1);
expect(out.width).toBe(400);
expect(out.height).toBe(400);
@@ -89,39 +89,39 @@ describe('соотношение сторон', () => {
});
});
describe('forceOrientation / symmetricCopy', () => {
it('широкое становится высоким поворотом', () => {
describe("forceOrientation / symmetricCopy", () => {
it("широкое становится высоким поворотом", () => {
const wide = makeImage(300, 100, new Array(30000).fill([5, 5, 5, 255]));
const out = forceOrientation(wide, 'portrait');
const out = forceOrientation(wide, "portrait");
expect(out.width).toBe(100);
expect(out.height).toBe(300);
});
it('квадрат не поворачивается', () => {
it("квадрат не поворачивается", () => {
const sq = makeImage(50, 50, new Array(2500).fill([5, 5, 5, 255]));
const out = forceOrientation(sq, 'portrait');
const out = forceOrientation(sq, "portrait");
expect(out.width).toBe(50);
expect(out.height).toBe(50);
});
it('симметричная копия удваивает ширину и зеркалит правую половину', () => {
it("симметричная копия удваивает ширину и зеркалит правую половину", () => {
const img = makeImage(2, 1, [
[10, 0, 0, 255],
[20, 0, 0, 255]
[20, 0, 0, 255],
]);
const out = symmetricCopy(img, 'vertical', 'left');
const out = symmetricCopy(img, "vertical", "left");
expect(out.width).toBe(4);
expect(out.data[0]).toBe(10);
expect(out.data[8]).toBe(20); // пиксель 2 = зеркало начала
expect(out.data[12]).toBe(10); // пиксель 3 = зеркало конца
});
it('вертикальная ось удваивает высоту', () => {
it("вертикальная ось удваивает высоту", () => {
const img = makeImage(1, 2, [
[10, 0, 0, 255],
[30, 0, 0, 255]
[30, 0, 0, 255],
]);
const out = symmetricCopy(img, 'horizontal', 'top');
const out = symmetricCopy(img, "horizontal", "top");
expect(out.height).toBe(4);
expect(out.data[(2 * 1 + 0) * 4]).toBe(30); // строка 2 = зеркало строки 1
expect(out.data[(3 * 1 + 0) * 4]).toBe(10); // строка 3 = зеркало строки 0
+16 -16
View File
@@ -1,23 +1,23 @@
import { describe, expect, it } from 'vitest';
import { colorSpectrum, drawGrid, randomColorBlocks } from './gen-tools';
import { describe, expect, it } from "vitest";
import { colorSpectrum, drawGrid, randomColorBlocks } from "./gen-tools";
describe('colorSpectrum', () => {
it('горизонтальный: левый край красный (hue 0)', () => {
const img = colorSpectrum(100, 10, 'horizontal', 100, 50);
describe("colorSpectrum", () => {
it("горизонтальный: левый край красный (hue 0)", () => {
const img = colorSpectrum(100, 10, "horizontal", 100, 50);
expect(img.data[0]).toBeGreaterThan(200);
expect(img.data[1]).toBeLessThan(60);
});
it('вертикальный: зелёный максимум около hue 120°', () => {
const img = colorSpectrum(10, 100, 'vertical', 100, 50);
it("вертикальный: зелёный максимум около hue 120°", () => {
const img = colorSpectrum(10, 100, "vertical", 100, 50);
const rowHue120 = Math.round((120 / 360) * 99);
const g = img.data[(rowHue120 * 10 + 5) * 4 + 1];
expect(g).toBeGreaterThan(200);
});
});
describe('randomColorBlocks', () => {
it('детерминирован по seed и блоки однотонные', () => {
describe("randomColorBlocks", () => {
it("детерминирован по seed и блоки однотонные", () => {
const a = randomColorBlocks(64, 64, 16, 7);
const b = randomColorBlocks(64, 64, 16, 7);
expect([...a.data]).toEqual([...b.data]);
@@ -27,18 +27,18 @@ describe('randomColorBlocks', () => {
});
});
describe('drawGrid', () => {
it('линии на пересечениях непрозрачны, фон прозрачен', () => {
const out = drawGrid(100, 100, 4, 4, 2, '#000000', true);
describe("drawGrid", () => {
it("линии на пересечениях непрозрачны, фон прозрачен", () => {
const out = drawGrid(100, 100, 4, 4, 2, "#000000", true);
expect(out.data[0]).toBe(0);
expect(out.data[3]).toBe(255); // (0,0) на линии
const mid = ((53 * 100) + 53) * 4;
const mid = (53 * 100 + 53) * 4;
expect(out.data[mid + 3]).toBe(0); // между линиями прозрачн
});
it('белый непрозрачный фон при transparentBg=false', () => {
const out = drawGrid(20, 20, 2, 2, 1, '#000000', false);
const mid = ((5 * 20) + 5) * 4;
it("белый непрозрачный фон при transparentBg=false", () => {
const out = drawGrid(20, 20, 2, 2, 1, "#000000", false);
const mid = (5 * 20 + 5) * 4;
expect(out.data[mid]).toBe(255);
});
});
+18 -11
View File
@@ -1,23 +1,26 @@
import { createPixelImage, type PixelImage } from './types';
import { hslToRgb } from './palette';
import { mulberry32 } from './pixel-fx';
import { createPixelImage, type PixelImage } from "./types";
import { hslToRgb } from "./palette";
import { mulberry32 } from "./pixel-fx";
/** Радужный спектр: оттенок 0..360 вдоль выбранной оси. */
export function colorSpectrum(
width: number,
height: number,
direction: 'horizontal' | 'vertical',
direction: "horizontal" | "vertical",
saturationPercent: number,
lightnessPercent: number
lightnessPercent: number,
): PixelImage {
const out = createPixelImage(width, height);
for (let y = 0; y < height; y++) {
for (let x = 0; x < width; x++) {
const t = direction === 'vertical' ? y / Math.max(1, height - 1) : x / Math.max(1, width - 1);
const t =
direction === "vertical"
? y / Math.max(1, height - 1)
: x / Math.max(1, width - 1);
const { r, g, b } = hslToRgb({
h: t * 360,
s: saturationPercent / 100,
l: lightnessPercent / 100
l: lightnessPercent / 100,
});
const di = (y * width + x) * 4;
out.data[di] = r;
@@ -34,7 +37,7 @@ export function randomColorBlocks(
width: number,
height: number,
blockSize: number,
seed: number
seed: number,
): PixelImage {
const bs = Math.max(1, Math.round(blockSize));
const out = createPixelImage(width, height);
@@ -44,7 +47,7 @@ export function randomColorBlocks(
const { r, g, b } = hslToRgb({
h: rng() * 360,
s: 0.65 + rng() * 0.35,
l: 0.45 + rng() * 0.25
l: 0.45 + rng() * 0.25,
});
const yMax = Math.min(by + bs, height);
const xMax = Math.min(bx + bs, width);
@@ -62,7 +65,11 @@ export function randomColorBlocks(
return out;
}
function lineMask(length: number, divisions: number, lineWidth: number): Uint8Array {
function lineMask(
length: number,
divisions: number,
lineWidth: number,
): Uint8Array {
const mask = new Uint8Array(length);
const lw = Math.max(1, Math.round(lineWidth));
for (let i = 0; i <= divisions; i++) {
@@ -80,7 +87,7 @@ export function drawGrid(
rows: number,
lineWidth: number,
colorHex: string,
transparentBg: boolean
transparentBg: boolean,
): PixelImage {
const out = createPixelImage(width, height);
if (!transparentBg) out.data.fill(255);
+18 -16
View File
@@ -1,8 +1,8 @@
import { describe, expect, it } from 'vitest';
import { gradientImage, noiseImage, solidImage } from './generate';
import { describe, expect, it } from "vitest";
import { gradientImage, noiseImage, solidImage } from "./generate";
describe('solidImage', () => {
it('заливает весь холст заданным цветом', () => {
describe("solidImage", () => {
it("заливает весь холст заданным цветом", () => {
const out = solidImage(2, 2, [10, 20, 30, 255]);
expect(out.width).toBe(2);
expect([...out.data]).toEqual(new Array(4).fill([10, 20, 30, 255]).flat());
@@ -12,24 +12,26 @@ describe('solidImage', () => {
[0, 10],
[10, 0],
[2.5, 10],
[-1, 5]
])('бросает ошибку на размерах %i x %i', (w, h) => {
[-1, 5],
])("бросает ошибку на размерах %i x %i", (w, h) => {
expect(() => solidImage(w, h, [0, 0, 0, 255])).toThrow();
});
});
describe('noiseImage', () => {
it('детерминирован: одно зерно — одни байты', () => {
expect([...noiseImage(4, 4, 42).data]).toEqual([...noiseImage(4, 4, 42).data]);
describe("noiseImage", () => {
it("детерминирован: одно зерно — одни байты", () => {
expect([...noiseImage(4, 4, 42).data]).toEqual([
...noiseImage(4, 4, 42).data,
]);
});
it('разные зерна дают разные данные', () => {
it("разные зерна дают разные данные", () => {
const a = [...noiseImage(8, 8, 1).data];
const b = [...noiseImage(8, 8, 2).data];
expect(a).not.toEqual(b);
});
it('альфа всегда непрозрачная', () => {
it("альфа всегда непрозрачная", () => {
const data = noiseImage(3, 3, 7).data;
for (let i = 3; i < data.length; i += 4) {
expect(data[i]).toBe(255);
@@ -37,14 +39,14 @@ describe('noiseImage', () => {
});
});
describe('gradientImage', () => {
it('горизонтальный градиент идёт от цвета A к цвету B', () => {
describe("gradientImage", () => {
it("горизонтальный градиент идёт от цвета A к цвету B", () => {
const out = gradientImage(
3,
1,
[0, 0, 0, 255],
[255, 255, 255, 255],
'horizontal'
"horizontal",
);
const px = (x: number) => [...out.data.slice(x * 4, x * 4 + 4)];
expect(px(0)).toEqual([0, 0, 0, 255]);
@@ -52,13 +54,13 @@ describe('gradientImage', () => {
expect(px(2)).toEqual([255, 255, 255, 255]);
});
it('вертикальный градиент меняется по строкам', () => {
it("вертикальный градиент меняется по строкам", () => {
const out = gradientImage(
1,
2,
[0, 0, 0, 255],
[100, 100, 100, 255],
'vertical'
"vertical",
);
expect(out.data[0]).toBe(0);
expect(out.data[4]).toBe(100);
+33 -14
View File
@@ -1,13 +1,18 @@
import type { PixelImage } from './types';
import { ToolError } from './errors';
import type { PixelImage } from "./types";
import { ToolError } from "./errors";
export function solidImage(
width: number,
height: number,
rgba: [number, number, number, number]
rgba: [number, number, number, number],
): PixelImage {
if (!Number.isInteger(width) || !Number.isInteger(height) || width < 1 || height < 1) {
throw new ToolError('errors.sizeInt');
if (
!Number.isInteger(width) ||
!Number.isInteger(height) ||
width < 1 ||
height < 1
) {
throw new ToolError("errors.sizeInt");
}
const data = new Uint8ClampedArray(width * height * 4);
for (let i = 0; i < data.length; i += 4) {
@@ -19,9 +24,18 @@ export function solidImage(
return { width, height, data };
}
export function noiseImage(width: number, height: number, seed: number): PixelImage {
if (!Number.isInteger(width) || !Number.isInteger(height) || width < 1 || height < 1) {
throw new ToolError('errors.sizeInt');
export function noiseImage(
width: number,
height: number,
seed: number,
): PixelImage {
if (
!Number.isInteger(width) ||
!Number.isInteger(height) ||
width < 1 ||
height < 1
) {
throw new ToolError("errors.sizeInt");
}
const random = mulberry32(seed);
const data = new Uint8ClampedArray(width * height * 4);
@@ -39,20 +53,25 @@ export function gradientImage(
height: number,
fromRgba: [number, number, number, number],
toRgba: [number, number, number, number],
direction: 'horizontal' | 'vertical'
direction: "horizontal" | "vertical",
): PixelImage {
if (!Number.isInteger(width) || !Number.isInteger(height) || width < 1 || height < 1) {
throw new ToolError('errors.sizeInt');
if (
!Number.isInteger(width) ||
!Number.isInteger(height) ||
width < 1 ||
height < 1
) {
throw new ToolError("errors.sizeInt");
}
const out: PixelImage = {
width,
height,
data: new Uint8ClampedArray(width * height * 4)
data: new Uint8ClampedArray(width * height * 4),
};
const steps = (direction === 'horizontal' ? width : height) - 1;
const steps = (direction === "horizontal" ? width : height) - 1;
for (let y = 0; y < height; y++) {
for (let x = 0; x < width; x++) {
const t = steps === 0 ? 0 : (direction === 'horizontal' ? x : y) / steps;
const t = steps === 0 ? 0 : (direction === "horizontal" ? x : y) / steps;
const i = (y * width + x) * 4;
out.data[i] = fromRgba[0] + (toRgba[0] - fromRgba[0]) * t;
out.data[i + 1] = fromRgba[1] + (toRgba[1] - fromRgba[1]) * t;
+60 -63
View File
@@ -1,94 +1,90 @@
import { describe, expect, it } from 'vitest';
import { centerByAlpha, crop, expandCanvas, flip, resize, rotate90, tile } from './geometry';
import { makeImage } from './test-helpers';
import { describe, expect, it } from "vitest";
import {
centerByAlpha,
crop,
expandCanvas,
flip,
resize,
rotate90,
tile,
} from "./geometry";
import { makeImage } from "./test-helpers";
const square = () =>
makeImage(2, 2, [
[1, 1, 1, 1],
[2, 2, 2, 2],
[3, 3, 3, 3],
[4, 4, 4, 4]
[4, 4, 4, 4],
]);
describe('flip', () => {
it('отражает по горизонтали (зеркало слева-направо)', () => {
const out = flip(square(), 'horizontal');
describe("flip", () => {
it("отражает по горизонтали (зеркало слева-направо)", () => {
const out = flip(square(), "horizontal");
expect(out.width).toBe(2);
expect(out.height).toBe(2);
expect([...out.data]).toEqual([
2, 2, 2, 2,
1, 1, 1, 1,
4, 4, 4, 4,
3, 3, 3, 3
2, 2, 2, 2, 1, 1, 1, 1, 4, 4, 4, 4, 3, 3, 3, 3,
]);
});
it('отражает по вертикали (сверху-вниз)', () => {
const out = flip(square(), 'vertical');
it("отражает по вертикали (сверху-вниз)", () => {
const out = flip(square(), "vertical");
expect([...out.data]).toEqual([
3, 3, 3, 3,
4, 4, 4, 4,
1, 1, 1, 1,
2, 2, 2, 2
3, 3, 3, 3, 4, 4, 4, 4, 1, 1, 1, 1, 2, 2, 2, 2,
]);
});
it('не мутирует вход', () => {
it("не мутирует вход", () => {
const img = square();
flip(img, 'horizontal');
expect([...img.data]).toEqual([1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4]);
flip(img, "horizontal");
expect([...img.data]).toEqual([
1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4,
]);
});
});
describe('rotate90', () => {
it('поворачивает неквадрат 2x3 на 90° по часовой', () => {
describe("rotate90", () => {
it("поворачивает неквадрат 2x3 на 90° по часовой", () => {
const rect = makeImage(2, 3, [
[1, 1, 1, 1],
[2, 2, 2, 2],
[3, 3, 3, 3],
[4, 4, 4, 4],
[5, 5, 5, 5],
[6, 6, 6, 6]
[6, 6, 6, 6],
]);
const out = rotate90(rect, 1);
expect(out.width).toBe(3);
expect(out.height).toBe(2);
expect([...out.data]).toEqual([
5, 5, 5, 5,
3, 3, 3, 3,
1, 1, 1, 1,
6, 6, 6, 6,
4, 4, 4, 4,
2, 2, 2, 2
5, 5, 5, 5, 3, 3, 3, 3, 1, 1, 1, 1, 6, 6, 6, 6, 4, 4, 4, 4, 2, 2, 2, 2,
]);
});
it('turns=0 возвращает копию без изменений', () => {
it("turns=0 возвращает копию без изменений", () => {
const img = square();
const out = rotate90(img, 0);
expect(out).not.toBe(img);
expect([...out.data]).toEqual([...img.data]);
});
it('нормализует turns: 5 ≡ 1, -3 ≡ 1, 4 ≡ 0', () => {
it("нормализует turns: 5 ≡ 1, -3 ≡ 1, 4 ≡ 0", () => {
const once = [...rotate90(square(), 1).data];
expect([...rotate90(square(), 5).data]).toEqual(once);
expect([...rotate90(square(), -3).data]).toEqual(once);
expect([...rotate90(square(), 4).data]).toEqual([...square().data]);
});
it('turns=2 на квадрате равно двойному отражению', () => {
it("turns=2 на квадрате равно двойному отражению", () => {
const out = rotate90(square(), 2);
expect([...out.data]).toEqual([
4, 4, 4, 4,
3, 3, 3, 3,
2, 2, 2, 2,
1, 1, 1, 1
4, 4, 4, 4, 3, 3, 3, 3, 2, 2, 2, 2, 1, 1, 1, 1,
]);
});
});
describe('crop', () => {
describe("crop", () => {
const grid = () =>
makeImage(3, 3, [
[1, 1, 1, 1],
@@ -99,63 +95,64 @@ describe('crop', () => {
[6, 6, 6, 6],
[7, 7, 7, 7],
[8, 8, 8, 8],
[9, 9, 9, 9]
[9, 9, 9, 9],
]);
it('вырезает центральную область 2x2 из 3x3', () => {
it("вырезает центральную область 2x2 из 3x3", () => {
const out = crop(grid(), 1, 1, 2, 2);
expect(out.width).toBe(2);
expect(out.height).toBe(2);
expect([...out.data]).toEqual([
5, 5, 5, 5,
6, 6, 6, 6,
8, 8, 8, 8,
9, 9, 9, 9
5, 5, 5, 5, 6, 6, 6, 6, 8, 8, 8, 8, 9, 9, 9, 9,
]);
});
it('усекает область, выходящую за границы', () => {
it("усекает область, выходящую за границы", () => {
const out = crop(grid(), -1, -1, 2, 2);
expect(out.width).toBe(1);
expect(out.height).toBe(1);
expect([...out.data]).toEqual([1, 1, 1, 1]);
});
it('бросает ToolError для области вне изображения', () => {
it("бросает ToolError для области вне изображения", () => {
expect(() => crop(grid(), 5, 5, 2, 2)).toThrow(/errors\.cropBounds/);
});
});
describe('expandCanvas', () => {
describe("expandCanvas", () => {
const pixel = () => makeImage(1, 1, [[10, 20, 30, 255]]);
it('прозрачное расширение кладёт пиксель со смещением', () => {
it("прозрачное расширение кладёт пиксель со смещением", () => {
const out = expandCanvas(pixel(), 1, 2, 3, 4);
expect(out.width).toBe(5);
expect(out.height).toBe(7);
expect([...out.data.slice(0, 4)]).toEqual([0, 0, 0, 0]);
expect([...out.data.slice((2 * 5 + 1) * 4, (2 * 5 + 1) * 4 + 4)]).toEqual([10, 20, 30, 255]);
expect([...out.data.slice((2 * 5 + 1) * 4, (2 * 5 + 1) * 4 + 4)]).toEqual([
10, 20, 30, 255,
]);
});
it('цветной фон заливает всё вокруг', () => {
const out = expandCanvas(pixel(), 1, 0, 0, 0, '#ffffff');
it("цветной фон заливает всё вокруг", () => {
const out = expandCanvas(pixel(), 1, 0, 0, 0, "#ffffff");
expect(out.data[0]).toBe(255);
expect(out.data[3]).toBe(255);
expect(out.data[(0 * 2 + 1) * 4 + 3]).toBe(255);
});
});
describe('tile', () => {
it('повторяет изображение по сетке', () => {
describe("tile", () => {
it("повторяет изображение по сетке", () => {
const out = tile(makeImage(1, 1, [[9, 9, 9, 255]]), 3, 2);
expect(out.width).toBe(3);
expect(out.height).toBe(2);
expect([...out.data].filter((_, i) => i % 4 === 0)).toEqual([9, 9, 9, 9, 9, 9]);
expect([...out.data].filter((_, i) => i % 4 === 0)).toEqual([
9, 9, 9, 9, 9, 9,
]);
});
});
describe('centerByAlpha', () => {
it('вырезает непрозрачный блок и центрирует на прежнем холсте', () => {
describe("centerByAlpha", () => {
it("вырезает непрозрачный блок и центрирует на прежнем холсте", () => {
const img = makeImage(3, 3, [
[0, 0, 0, 0],
[0, 0, 0, 0],
@@ -165,7 +162,7 @@ describe('centerByAlpha', () => {
[0, 0, 0, 0],
[0, 0, 0, 0],
[0, 0, 0, 0],
[0, 0, 0, 0]
[0, 0, 0, 0],
]);
const out = centerByAlpha(img);
expect(out.width).toBe(3);
@@ -175,30 +172,30 @@ describe('centerByAlpha', () => {
expect(alphaAt(1, 1)).toBe(255);
});
it('полностью прозрачное изображение возвращается без изменений', () => {
it("полностью прозрачное изображение возвращается без изменений", () => {
const img = makeImage(2, 1, [
[0, 0, 0, 0],
[0, 0, 0, 0]
[0, 0, 0, 0],
]);
expect([...centerByAlpha(img).data]).toEqual([...img.data]);
});
});
describe('resize', () => {
describe("resize", () => {
const twoByTwo = () =>
makeImage(2, 2, [
[0, 0, 0, 255],
[100, 100, 100, 255],
[200, 200, 200, 255],
[255, 255, 255, 255]
[255, 255, 255, 255],
]);
it('совпадает с входом при тех же размерах', () => {
it("совпадает с входом при тех же размерах", () => {
const img = twoByTwo();
expect([...resize(img, 2, 2).data]).toEqual([...img.data]);
});
it('апскейл 2x2 -> 4x4 билинейно интерполирует', () => {
it("апскейл 2x2 -> 4x4 билинейно интерполирует", () => {
const out = resize(twoByTwo(), 4, 4);
expect(out.width).toBe(4);
expect(out.height).toBe(4);
@@ -207,7 +204,7 @@ describe('resize', () => {
expect(red.slice(4, 8)).toEqual([50, 72, 117, 139]);
});
it('бросает ToolError на некорректные размеры', () => {
it("бросает ToolError на некорректные размеры", () => {
const img = twoByTwo();
expect(() => resize(img, 0, 10)).toThrow(/errors\.sizeInt/);
expect(() => resize(img, 10.5, 10)).toThrow(/errors\.sizeInt/);
+77 -43
View File
@@ -1,6 +1,6 @@
import { parseHex } from './alpha';
import { ToolError } from './errors';
import { clonePixelImage, createPixelImage, type PixelImage } from './types';
import { parseHex } from "./alpha";
import { ToolError } from "./errors";
import { clonePixelImage, createPixelImage, type PixelImage } from "./types";
export function expandCanvas(
img: PixelImage,
@@ -8,7 +8,7 @@ export function expandCanvas(
top: number,
right: number,
bottom: number,
backgroundHex?: string
backgroundHex?: string,
): PixelImage {
const l = Math.max(0, Math.trunc(left));
const t = Math.max(0, Math.trunc(top));
@@ -28,13 +28,17 @@ export function expandCanvas(
const srcStart = y * img.width * 4;
out.data.set(
img.data.subarray(srcStart, srcStart + img.width * 4),
((y + t) * out.width + l) * 4
((y + t) * out.width + l) * 4,
);
}
return out;
}
export function tile(img: PixelImage, columns: number, rows: number): PixelImage {
export function tile(
img: PixelImage,
columns: number,
rows: number,
): PixelImage {
const cols = Math.max(1, Math.trunc(columns));
const rowsCount = Math.max(1, Math.trunc(rows));
const out = createPixelImage(img.width * cols, img.height * rowsCount);
@@ -44,7 +48,7 @@ export function tile(img: PixelImage, columns: number, rows: number): PixelImage
const srcStart = y * img.width * 4;
out.data.set(
img.data.subarray(srcStart, srcStart + img.width * 4),
((ty * img.height + y) * out.width + tx * img.width) * 4
((ty * img.height + y) * out.width + tx * img.width) * 4,
);
}
}
@@ -75,20 +79,20 @@ export function centerByAlpha(img: PixelImage): PixelImage {
for (let y = 0; y < content.height; y++) {
out.data.set(
content.data.subarray(y * content.width * 4, (y + 1) * content.width * 4),
((y + dy) * out.width + dx) * 4
((y + dy) * out.width + dx) * 4,
);
}
return out;
}
export type FlipAxis = 'horizontal' | 'vertical';
export type FlipAxis = "horizontal" | "vertical";
export function flip(img: PixelImage, axis: FlipAxis): PixelImage {
const out = createPixelImage(img.width, img.height);
for (let y = 0; y < img.height; y++) {
for (let x = 0; x < img.width; x++) {
const sx = axis === 'horizontal' ? img.width - 1 - x : x;
const sy = axis === 'vertical' ? img.height - 1 - y : y;
const sx = axis === "horizontal" ? img.width - 1 - x : x;
const sy = axis === "vertical" ? img.height - 1 - y : y;
copyPixel(img, sx, sy, out, x, y);
}
}
@@ -120,7 +124,7 @@ export function crop(
x: number,
y: number,
width: number,
height: number
height: number,
): PixelImage {
const sx = clampInt(x, 0, img.width);
const sy = clampInt(y, 0, img.height);
@@ -129,7 +133,7 @@ export function crop(
const w = ex - sx;
const h = ey - sy;
if (w <= 0 || h <= 0) {
throw new ToolError('errors.cropBounds');
throw new ToolError("errors.cropBounds");
}
const out = createPixelImage(w, h);
for (let row = 0; row < h; row++) {
@@ -139,9 +143,18 @@ export function crop(
return out;
}
export function resize(img: PixelImage, width: number, height: number): PixelImage {
if (!Number.isInteger(width) || !Number.isInteger(height) || width < 1 || height < 1) {
throw new ToolError('errors.sizeInt');
export function resize(
img: PixelImage,
width: number,
height: number,
): PixelImage {
if (
!Number.isInteger(width) ||
!Number.isInteger(height) ||
width < 1 ||
height < 1
) {
throw new ToolError("errors.sizeInt");
}
const out = createPixelImage(width, height);
const xr = img.width / width;
@@ -173,7 +186,14 @@ export function resize(img: PixelImage, width: number, height: number): PixelIma
return out;
}
function copyPixel(src: PixelImage, sx: number, sy: number, dst: PixelImage, dx: number, dy: number): void {
function copyPixel(
src: PixelImage,
sx: number,
sy: number,
dst: PixelImage,
dx: number,
dy: number,
): void {
const si = (sy * src.width + sx) * 4;
const di = (dy * dst.width + dx) * 4;
dst.data[di] = src.data[si];
@@ -185,7 +205,7 @@ function copyPixel(src: PixelImage, sx: number, sy: number, dst: PixelImage, dx:
export function sampleBilinear(
img: PixelImage,
fx: number,
fy: number
fy: number,
): [number, number, number, number] {
const maxX = img.width - 1;
const maxY = img.height - 1;
@@ -213,24 +233,22 @@ export function sampleBilinear(
function clampInt(value: number, min: number, max: number): number {
return Math.min(max, Math.max(min, Math.trunc(value)));
}
export type Anchor9 =
| 'top-left'
| 'top-center'
| 'top-right'
| 'middle-left'
| 'center'
| 'middle-right'
| 'bottom-left'
| 'bottom-center'
| 'bottom-right';
| "top-left"
| "top-center"
| "top-right"
| "middle-left"
| "center"
| "middle-right"
| "bottom-left"
| "bottom-center"
| "bottom-right";
/** Границы контента: пиксели с альфой строго больше порога. Пустое изображение → null. */
export function contentBounds(
img: PixelImage,
alphaThreshold = 0
alphaThreshold = 0,
): { x: number; y: number; w: number; h: number } | null {
let minX = img.width;
let minY = img.height;
@@ -262,11 +280,19 @@ export function changeCanvasSize(
img: PixelImage,
width: number,
height: number,
anchor: Anchor9
anchor: Anchor9,
): PixelImage {
const out = createPixelImage(width, height);
const pasteX = anchor.endsWith('-left') ? 0 : anchor.endsWith('-right') ? width - img.width : Math.floor((width - img.width) / 2);
const pasteY = anchor.startsWith('top-') ? 0 : anchor.startsWith('bottom-') ? height - img.height : Math.floor((height - img.height) / 2);
const pasteX = anchor.endsWith("-left")
? 0
: anchor.endsWith("-right")
? width - img.width
: Math.floor((width - img.width) / 2);
const pasteY = anchor.startsWith("top-")
? 0
: anchor.startsWith("bottom-")
? height - img.height
: Math.floor((height - img.height) / 2);
for (let y = 0; y < height; y++) {
const sy = y - pasteY;
if (sy < 0 || sy >= img.height) continue;
@@ -307,13 +333,21 @@ export function padToRatio(img: PixelImage, ratio: number): PixelImage {
else if (current < ratio) w = Math.round(h * ratio);
w = Math.max(1, w);
h = Math.max(1, h);
return changeCanvasSize(img, w, h, 'center');
return changeCanvasSize(img, w, h, "center");
}
/** Разворачивает изображение на 90°, если его ориентация не совпадает с целевой. Квадрат не трогает. */
export function forceOrientation(img: PixelImage, target: 'portrait' | 'landscape'): PixelImage {
const current = img.width > img.height ? 'landscape' : img.width < img.height ? 'portrait' : 'square';
if (current === target || current === 'square') return clonePixelImage(img);
export function forceOrientation(
img: PixelImage,
target: "portrait" | "landscape",
): PixelImage {
const current =
img.width > img.height
? "landscape"
: img.width < img.height
? "portrait"
: "square";
if (current === target || current === "square") return clonePixelImage(img);
return rotate90(img, 1);
}
@@ -323,14 +357,14 @@ export function forceOrientation(img: PixelImage, target: 'portrait' | 'landscap
*/
export function symmetricCopy(
img: PixelImage,
axis: 'vertical' | 'horizontal',
keepSide: 'left' | 'right' | 'top' | 'bottom'
axis: "vertical" | "horizontal",
keepSide: "left" | "right" | "top" | "bottom",
): PixelImage {
if (axis === 'vertical') {
if (axis === "vertical") {
const out = createPixelImage(img.width * 2, img.height);
for (let y = 0; y < img.height; y++) {
for (let x = 0; x < img.width; x++) {
const srcX = keepSide === 'left' ? x : img.width - 1 - x;
const srcX = keepSide === "left" ? x : img.width - 1 - x;
const di = (y * out.width + x) * 4;
const si = (y * img.width + srcX) * 4;
out.data[di] = img.data[si];
@@ -349,7 +383,7 @@ export function symmetricCopy(
}
const out = createPixelImage(img.width, img.height * 2);
for (let y = 0; y < img.height; y++) {
const srcY = keepSide === 'top' ? y : img.height - 1 - y;
const srcY = keepSide === "top" ? y : img.height - 1 - y;
for (let x = 0; x < img.width; x++) {
const si = (srcY * img.width + x) * 4;
const dTop = (y * out.width + x) * 4;
@@ -366,4 +400,4 @@ export function symmetricCopy(
}
}
return out;
}
}
+30 -22
View File
@@ -1,32 +1,40 @@
import { describe, expect, it } from 'vitest';
import { isSupportedImage, unsupportedImageError } from './io';
import { describe, expect, it } from "vitest";
import { isSupportedImage, unsupportedImageError } from "./io";
describe('isSupportedImage', () => {
it.each(['image/png', 'image/jpeg', 'image/webp', 'image/gif', 'image/bmp', 'image/x-icon'])(
'принимает %s',
(type) => {
expect(isSupportedImage(new File([], 'x', { type }))).toBe(true);
}
);
it('отклоняет неподдерживаемый тип', () => {
expect(isSupportedImage(new File([], 'a.txt', { type: 'text/plain' }))).toBe(false);
describe("isSupportedImage", () => {
it.each([
"image/png",
"image/jpeg",
"image/webp",
"image/gif",
"image/bmp",
"image/x-icon",
])("принимает %s", (type) => {
expect(isSupportedImage(new File([], "x", { type }))).toBe(true);
});
it('отклоняет файл без типа', () => {
expect(isSupportedImage(new File([], 'x'))).toBe(false);
it("отклоняет неподдерживаемый тип", () => {
expect(
isSupportedImage(new File([], "a.txt", { type: "text/plain" })),
).toBe(false);
});
it("отклоняет файл без типа", () => {
expect(isSupportedImage(new File([], "x"))).toBe(false);
});
});
describe('unsupportedImageError', () => {
it('ключ ошибки и тип файла в vars', () => {
const err = unsupportedImageError(new File([], 'a.txt', { type: 'text/plain' }));
expect(err.key).toBe('errors.unsupportedFile');
expect(err.vars?.type).toBe('text/plain');
describe("unsupportedImageError", () => {
it("ключ ошибки и тип файла в vars", () => {
const err = unsupportedImageError(
new File([], "a.txt", { type: "text/plain" }),
);
expect(err.key).toBe("errors.unsupportedFile");
expect(err.vars?.type).toBe("text/plain");
});
it('пустой тип передаётся как unknown', () => {
const err = unsupportedImageError(new File([], 'x'));
expect(err.vars?.type).toBe('unknown');
it("пустой тип передаётся как unknown", () => {
const err = unsupportedImageError(new File([], "x"));
expect(err.vars?.type).toBe("unknown");
});
});
+71 -47
View File
@@ -1,33 +1,40 @@
import { encodeBmpBytes } from './bmp';
import { ToolError } from './errors';
import { type PixelImage } from './types';
import { encodeBmpBytes } from "./bmp";
import { ToolError } from "./errors";
import { type PixelImage } from "./types";
export type OutputMime = 'image/png' | 'image/jpeg' | 'image/webp' | 'image/bmp';
export type OutputMime =
"image/png" | "image/jpeg" | "image/webp" | "image/bmp";
export const ACCEPTED_IMAGE_TYPES =
'image/png,image/jpeg,image/webp,image/gif,image/bmp,image/x-icon';
"image/png,image/jpeg,image/webp,image/gif,image/bmp,image/x-icon";
const SUPPORTED_MIME_TYPES = new Set(ACCEPTED_IMAGE_TYPES.split(','));
const SUPPORTED_MIME_TYPES = new Set(ACCEPTED_IMAGE_TYPES.split(","));
export function isSupportedImage(file: File): boolean {
return SUPPORTED_MIME_TYPES.has(file.type);
}
export function unsupportedImageError(file: File): ToolError {
return new ToolError('errors.unsupportedFile', { type: file.type || 'unknown' });
export function unsupportedImageError(file: File): ToolError {
return new ToolError("errors.unsupportedFile", {
type: file.type || "unknown",
});
}
async function decodeBitmap(bitmap: ImageBitmap): Promise<PixelImage> {
const canvas = document.createElement('canvas');
const canvas = document.createElement("canvas");
canvas.width = bitmap.width;
canvas.height = bitmap.height;
const ctx = canvas.getContext('2d', { willReadFrequently: true });
const ctx = canvas.getContext("2d", { willReadFrequently: true });
if (!ctx) {
throw new ToolError('errors.noCanvasCtx');
throw new ToolError("errors.noCanvasCtx");
}
ctx.drawImage(bitmap, 0, 0);
const imageData = ctx.getImageData(0, 0, canvas.width, canvas.height);
return { width: imageData.width, height: imageData.height, data: imageData.data };
return {
width: imageData.width,
height: imageData.height,
data: imageData.data,
};
}
export async function decodeFile(file: File): Promise<PixelImage> {
@@ -39,7 +46,9 @@ export async function decodeFile(file: File): Promise<PixelImage> {
}
}
export async function decodeBytes(bytes: Uint8Array<ArrayBuffer>): Promise<PixelImage> {
export async function decodeBytes(
bytes: Uint8Array<ArrayBuffer>,
): Promise<PixelImage> {
const blob = new Blob([bytes]);
const bitmap = await createImageBitmap(blob);
try {
@@ -50,25 +59,25 @@ export async function decodeBytes(bytes: Uint8Array<ArrayBuffer>): Promise<Pixel
}
export function toDataUrl(img: PixelImage): string {
const canvas = document.createElement('canvas');
const canvas = document.createElement("canvas");
canvas.width = img.width;
canvas.height = img.height;
const ctx = canvas.getContext('2d');
const ctx = canvas.getContext("2d");
if (!ctx) {
throw new ToolError('errors.noCanvasCtx');
throw new ToolError("errors.noCanvasCtx");
}
ctx.putImageData(new ImageData(img.data, img.width, img.height), 0, 0);
return canvas.toDataURL('image/png');
return canvas.toDataURL("image/png");
}
export function toBase64(img: PixelImage): string {
return toDataUrl(img).slice('data:image/png;base64,'.length);
return toDataUrl(img).slice("data:image/png;base64,".length);
}
export async function decodeTextImage(text: string): Promise<PixelImage> {
const cleaned = text.trim().replace(/^data:[^,]*,/, '');
const cleaned = text.trim().replace(/^data:[^,]*,/, "");
if (cleaned.length === 0) {
throw new ToolError('errors.badBase64');
throw new ToolError("errors.badBase64");
}
const binary = atob(cleaned);
const bytes = Uint8Array.from(binary, (ch) => ch.charCodeAt(0));
@@ -77,44 +86,48 @@ export async function decodeTextImage(text: string): Promise<PixelImage> {
export async function encode(
img: PixelImage,
mime: OutputMime = 'image/png',
quality?: number
mime: OutputMime = "image/png",
quality?: number,
): Promise<Blob> {
if (mime === 'image/bmp') {
if (mime === "image/bmp") {
return new Blob([encodeBmpBytes(img)], { type: mime });
}
if (mime === 'image/jpeg' || mime === 'image/webp') {
if (mime === "image/jpeg" || mime === "image/webp") {
if (quality !== undefined && (quality < 0 || quality > 1)) {
throw new ToolError('errors.qualityRange');
throw new ToolError("errors.qualityRange");
}
}
const canvas = document.createElement('canvas');
const canvas = document.createElement("canvas");
canvas.width = img.width;
canvas.height = img.height;
const ctx = canvas.getContext('2d');
const ctx = canvas.getContext("2d");
if (!ctx) {
throw new ToolError('errors.noCanvasCtx');
throw new ToolError("errors.noCanvasCtx");
}
ctx.putImageData(new ImageData(img.data, img.width, img.height), 0, 0);
return await canvasToBlob(canvas, mime, quality);
}
function canvasToBlob(canvas: HTMLCanvasElement, mime: OutputMime, quality?: number): Promise<Blob> {
function canvasToBlob(
canvas: HTMLCanvasElement,
mime: OutputMime,
quality?: number,
): Promise<Blob> {
return new Promise((resolve, reject) => {
canvas.toBlob(
(blob) =>
blob
? resolve(blob)
: reject(new ToolError('errors.encodeUnsupported', { mime })),
(blob) =>
blob
? resolve(blob)
: reject(new ToolError("errors.encodeUnsupported", { mime })),
mime,
quality
quality,
);
});
}
export function downloadBlob(blob: Blob, filename: string): void {
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
const a = document.createElement("a");
a.href = url;
a.download = filename;
document.body.append(a);
@@ -124,43 +137,54 @@ export function downloadBlob(blob: Blob, filename: string): void {
}
export function replaceExtension(filename: string, ext: string): string {
const base = filename.replace(/\.[^./\\]+$/, '');
const base = filename.replace(/\.[^./\\]+$/, "");
return `${base}.${ext}`;
}
export async function decodeSvgText(text: string, targetWidth?: number): Promise<PixelImage> {
export async function decodeSvgText(
text: string,
targetWidth?: number,
): Promise<PixelImage> {
const trimmed = text.trim();
if (trimmed.length === 0) {
throw new ToolError('errors.svgSize');
throw new ToolError("errors.svgSize");
}
const blob = new Blob([trimmed], { type: 'image/svg+xml' });
const blob = new Blob([trimmed], { type: "image/svg+xml" });
const url = URL.createObjectURL(blob);
try {
const img = new Image();
await new Promise<void>((resolve, reject) => {
img.onload = () => resolve();
img.onerror = () => reject(new ToolError('errors.svgLoad'));
img.onerror = () => reject(new ToolError("errors.svgLoad"));
img.src = url;
});
const w = targetWidth ?? img.naturalWidth ?? 300;
const ratio = img.naturalHeight > 0 ? img.naturalHeight / img.naturalWidth : 1;
const ratio =
img.naturalHeight > 0 ? img.naturalHeight / img.naturalWidth : 1;
const h = Math.max(1, Math.round(w * ratio));
const canvas = document.createElement('canvas');
const canvas = document.createElement("canvas");
canvas.width = w;
canvas.height = h;
const ctx = canvas.getContext('2d', { willReadFrequently: true });
if (!ctx) throw new ToolError('errors.noCanvasCtx');
const ctx = canvas.getContext("2d", { willReadFrequently: true });
if (!ctx) throw new ToolError("errors.noCanvasCtx");
ctx.drawImage(img, 0, 0, w, h);
const imageData = ctx.getImageData(0, 0, w, h);
return { width: imageData.width, height: imageData.height, data: imageData.data };
return {
width: imageData.width,
height: imageData.height,
data: imageData.data,
};
} finally {
URL.revokeObjectURL(url);
}
}
export async function jpegRoundtrip(img: PixelImage, qualityPercent: number): Promise<PixelImage> {
export async function jpegRoundtrip(
img: PixelImage,
qualityPercent: number,
): Promise<PixelImage> {
const quality = Math.min(Math.max(Math.trunc(qualityPercent), 1), 100) / 100;
const jpegBlob = await encode(img, 'image/jpeg', quality);
const jpegBlob = await encode(img, "image/jpeg", quality);
const bitmap = await createImageBitmap(jpegBlob);
try {
return await decodeBitmap(bitmap);
+26 -30
View File
@@ -1,79 +1,75 @@
import { describe, expect, it } from 'vitest';
import { describe, expect, it } from "vitest";
import {
extractByColor,
isGrayscaleish,
luma01,
rarityPredicate,
renderPredicateMask
} from './masks';
import { makeImage } from './test-helpers';
renderPredicateMask,
} from "./masks";
import { makeImage } from "./test-helpers";
const px = makeImage(2, 1, [
[255, 0, 0, 255],
[10, 10, 10, 255]
[10, 10, 10, 255],
]);
describe('isGrayscaleish / luma01', () => {
it('серый распознаётся с допуском, цветной — нет', () => {
describe("isGrayscaleish / luma01", () => {
it("серый распознаётся с допуском, цветной — нет", () => {
expect(isGrayscaleish(10, 10, 10, 0)).toBe(true);
expect(isGrayscaleish(12, 10, 11, 2)).toBe(true);
expect(isGrayscaleish(255, 0, 0, 0)).toBe(false);
});
it('luma01: белый 1, чёрный 0', () => {
it("luma01: белый 1, чёрный 0", () => {
expect(luma01(255, 255, 255)).toBeCloseTo(1);
expect(luma01(0, 0, 0)).toBeCloseTo(0);
});
});
describe('renderPredicateMask', () => {
it('binary: совпавшие белые на чёрном, альфа принудительная', () => {
const out = renderPredicateMask(
px,
(r) => r > 200,
{ mode: 'binary' }
);
describe("renderPredicateMask", () => {
it("binary: совпавшие белые на чёрном, альфа принудительная", () => {
const out = renderPredicateMask(px, (r) => r > 200, { mode: "binary" });
expect([...out.data.slice(0, 4)]).toEqual([255, 255, 255, 255]);
expect([...out.data.slice(4, 8)]).toEqual([0, 0, 0, 255]);
});
it('highlight: подкрашивает только совпавшие, остальные без изменений', () => {
const out = renderPredicateMask(
px,
(r) => r > 200,
{ mode: 'highlight', color: '#0000ff', opacityPercent: 100 }
);
it("highlight: подкрашивает только совпавшие, остальные без изменений", () => {
const out = renderPredicateMask(px, (r) => r > 200, {
mode: "highlight",
color: "#0000ff",
opacityPercent: 100,
});
expect([...out.data.slice(0, 4)]).toEqual([0, 0, 255, 255]);
expect([...out.data.slice(4, 8)]).toEqual([10, 10, 10, 255]);
});
it('прозрачность оригинала сохраняется в highlight-режиме', () => {
it("прозрачность оригинала сохраняется в highlight-режиме", () => {
const semi = makeImage(1, 1, [[200, 200, 200, 128]]);
const out = renderPredicateMask(semi, () => true, {
mode: 'highlight',
color: '#00ff00',
opacityPercent: 50
mode: "highlight",
color: "#00ff00",
opacityPercent: 50,
});
expect(out.data[3]).toBe(128);
expect(out.data[0]).toBeGreaterThan(90);
});
});
describe('rarityPredicate + extractByColor', () => {
describe("rarityPredicate + extractByColor", () => {
const img = makeImage(3, 1, [
[255, 0, 0, 255],
[255, 0, 0, 255],
[0, 255, 0, 255]
[0, 255, 0, 255],
]);
it('уникальный (единичный) цвет находится, массовый — нет', () => {
it("уникальный (единичный) цвет находится, массовый — нет", () => {
const pred = rarityPredicate(img, 1);
expect(pred(0, 255, 0, 255)).toBe(true);
expect(pred(255, 0, 0, 255)).toBe(false);
});
it('extractByColor оставляет близкие и делает дальние прозрачными', () => {
const out = extractByColor(px, '#0a0a0a', 5);
it("extractByColor оставляет близкие и делает дальние прозрачными", () => {
const out = extractByColor(px, "#0a0a0a", 5);
expect(out.data[3]).toBe(0);
expect(out.data[7]).toBe(255);
});
+36 -14
View File
@@ -1,8 +1,8 @@
import { hexToRgb } from './palette';
import type { PixelImage } from './types';
import { createPixelImage } from './types';
import { hexToRgb } from "./palette";
import type { PixelImage } from "./types";
import { createPixelImage } from "./types";
export type MaskMode = 'binary' | 'highlight';
export type MaskMode = "binary" | "highlight";
export interface MaskOptions {
/** binary: белое/чёрное без альфы; highlight: подкрасить совпавшие пиксели цветом. */
@@ -18,10 +18,10 @@ export interface MaskOptions {
export function renderPredicateMask(
img: PixelImage,
predicate: (r: number, g: number, b: number, a: number) => boolean,
o: MaskOptions = {}
o: MaskOptions = {},
): PixelImage {
const out = createPixelImage(img.width, img.height);
const highlight = o.mode !== 'binary';
const highlight = o.mode !== "binary";
const tint = o.color ? hexToRgb(o.color) : { r: 255, g: 0, b: 170 };
const opacity = Math.min(Math.max(o.opacityPercent ?? 70, 0), 100) / 100;
if (!highlight) {
@@ -34,7 +34,7 @@ export function renderPredicateMask(
const b = img.data[i + 2];
const a = img.data[i + 3];
if (!predicate(r, g, b, a)) {
if (highlight && o.mode === 'highlight') {
if (highlight && o.mode === "highlight") {
out.data[i] = r;
out.data[i + 1] = g;
out.data[i + 2] = b;
@@ -57,13 +57,27 @@ export function renderPredicateMask(
return out;
}
function maxChannelDelta(r1: number, g1: number, b1: number, r2: number, g2: number, b2: number): number {
function maxChannelDelta(
r1: number,
g1: number,
b1: number,
r2: number,
g2: number,
b2: number,
): number {
return Math.max(Math.abs(r1 - r2), Math.abs(g1 - g2), Math.abs(b1 - b2));
}
export function isGrayscaleish(r: number, g: number, b: number, tolerance: number): boolean {
export function isGrayscaleish(
r: number,
g: number,
b: number,
tolerance: number,
): boolean {
return (
Math.abs(r - g) <= tolerance && Math.abs(g - b) <= tolerance && Math.abs(r - b) <= tolerance
Math.abs(r - g) <= tolerance &&
Math.abs(g - b) <= tolerance &&
Math.abs(r - b) <= tolerance
);
}
@@ -78,13 +92,22 @@ export function luma01(r: number, g: number, b: number): number {
export function extractByColor(
img: PixelImage,
targetHex: string,
tolerancePercent: number
tolerancePercent: number,
): PixelImage {
const out = createPixelImage(img.width, img.height);
const t = hexToRgb(targetHex);
const tol = (Math.min(Math.max(tolerancePercent, 0), 100) / 100) * 255;
for (let i = 0; i < img.data.length; i += 4) {
if (maxChannelDelta(img.data[i], img.data[i + 1], img.data[i + 2], t.r, t.g, t.b) <= tol) {
if (
maxChannelDelta(
img.data[i],
img.data[i + 1],
img.data[i + 2],
t.r,
t.g,
t.b,
) <= tol
) {
out.data[i] = img.data[i];
out.data[i + 1] = img.data[i + 1];
out.data[i + 2] = img.data[i + 2];
@@ -99,7 +122,7 @@ export function extractByColor(
*/
export function rarityPredicate(
img: PixelImage,
limit: number
limit: number,
): (r: number, g: number, b: number, a: number) => boolean {
const counts = new Map<number, number>();
for (let i = 0; i < img.data.length; i += 4) {
@@ -111,4 +134,3 @@ export function rarityPredicate(
return (counts.get(key) ?? 0) <= limit;
};
}
+72 -49
View File
@@ -1,4 +1,4 @@
import { describe, expect, it } from 'vitest';
import { describe, expect, it } from "vitest";
import {
buildAlphaMask,
closingImage,
@@ -8,15 +8,15 @@ import {
erodeImage,
erodeMask,
openingImage,
strokeImage
} from './morphology';
import { makeImage } from './test-helpers';
strokeImage,
} from "./morphology";
import { makeImage } from "./test-helpers";
function maskFrom(rows: string[]): Uint8Array {
const flat = rows.join('');
const flat = rows.join("");
const mask = new Uint8Array(flat.length);
for (let i = 0; i < flat.length; i++) {
mask[i] = flat[i] === '#' ? 1 : 0;
mask[i] = flat[i] === "#" ? 1 : 0;
}
return mask;
}
@@ -24,66 +24,74 @@ function maskFrom(rows: string[]): Uint8Array {
function toRows(mask: Uint8Array, w: number): string[] {
const rows: string[] = [];
for (let y = 0; y < mask.length / w; y++) {
let row = '';
let row = "";
for (let x = 0; x < w; x++) {
row += mask[y * w + x] === 1 ? '#' : '.';
row += mask[y * w + x] === 1 ? "#" : ".";
}
rows.push(row);
}
return rows;
}
describe('dilateMask', () => {
it('одиночный пиксель r=1 превращается в плюс', () => {
describe("dilateMask", () => {
it("одиночный пиксель r=1 превращается в плюс", () => {
const out = dilateMask(
maskFrom(['.....', '.....', '..#..', '.....', '.....']),
maskFrom([".....", ".....", "..#..", ".....", "....."]),
5,
5,
1
1,
);
expect(toRows(out, 5)).toEqual(['.....', '..#..', '.###.', '..#..', '.....']);
expect(toRows(out, 5)).toEqual([
".....",
"..#..",
".###.",
"..#..",
".....",
]);
});
it('r=2 даёт ромб радиуса 2', () => {
it("r=2 даёт ромб радиуса 2", () => {
const out = dilateMask(
maskFrom(['.....', '.....', '..#..', '.....', '.....']),
maskFrom([".....", ".....", "..#..", ".....", "....."]),
5,
5,
2
2,
);
expect(toRows(out, 5)).toEqual(['..#..', '.###.', '#####', '.###.', '..#..']);
expect(toRows(out, 5)).toEqual([
"..#..",
".###.",
"#####",
".###.",
"..#..",
]);
});
});
describe('erodeMask', () => {
it('сплошной объект во весь кадр не сжимается от границ', () => {
const solid = maskFrom(['#####', '#####', '#####', '#####', '#####']);
describe("erodeMask", () => {
it("сплошной объект во весь кадр не сжимается от границ", () => {
const solid = maskFrom(["#####", "#####", "#####", "#####", "#####"]);
expect([...erodeMask(solid, 5, 5, 1)]).toEqual([...solid]);
});
it('изолированный пиксель исчезает', () => {
it("изолированный пиксель исчезает", () => {
const out = erodeMask(
maskFrom(['.....', '.....', '..#..', '.....', '.....']),
maskFrom([".....", ".....", "..#..", ".....", "....."]),
5,
5,
1
1,
);
expect([...out].every((v) => v === 0)).toBe(true);
});
});
describe('opening/closing образы', () => {
it('opening убирает отстоящий мусорный пиксель и сохраняет блок', () => {
describe("opening/closing образы", () => {
it("opening убирает отстоящий мусорный пиксель и сохраняет блок", () => {
const B = [10, 10, 10, 255];
const T = [0, 0, 0, 0];
const S = [200, 200, 200, 255];
const out = openingImage(
makeImage(
6,
3,
[B, B, B, T, S, T, B, B, B, T, T, T, B, B, B, T, T, T]
),
1
makeImage(6, 3, [B, B, B, T, S, T, B, B, B, T, T, T, B, B, B, T, T, T]),
1,
);
const at = (x: number, y: number) => out.data[(y * 6 + x) * 4 + 3];
expect(at(0, 1)).toBe(255);
@@ -91,7 +99,7 @@ describe('opening/closing образы', () => {
expect(at(4, 1)).toBe(0);
});
it('closing заполняет одиночную прозрачную дыру чёрным', () => {
it("closing заполняет одиночную прозрачную дыру чёрным", () => {
const pixels: number[][] = [];
for (let y = 0; y < 3; y++) {
for (let x = 0; x < 3; x++) {
@@ -104,27 +112,32 @@ describe('opening/closing образы', () => {
});
});
describe('image-обёртки', () => {
it('dilateImage сохраняет RGB содержимого, новые пиксели непрозрачны', () => {
describe("image-обёртки", () => {
it("dilateImage сохраняет RGB содержимого, новые пиксели непрозрачны", () => {
const T = [0, 0, 0, 0];
const O = [200, 50, 25, 255];
const img = makeImage(5, 2, [T, O, T, T, T, T, T, T, T, T]);
const out = dilateImage(img, 1);
const at = (x: number, y: number) => {
const di = (y * 5 + x) * 4;
return [out.data[di], out.data[di + 1], out.data[di + 2], out.data[di + 3]];
return [
out.data[di],
out.data[di + 1],
out.data[di + 2],
out.data[di + 3],
];
};
expect(at(1, 0)).toEqual([200, 50, 25, 255]);
expect(at(0, 0)).toEqual([0, 0, 0, 255]);
expect(at(4, 0)[3]).toBe(0);
});
it('erodeImage не стирает объект у края кадра', () => {
it("erodeImage не стирает объект у края кадра", () => {
const img = makeImage(2, 2, [
[10, 20, 30, 255],
[10, 20, 30, 255],
[10, 20, 30, 255],
[10, 20, 30, 255]
[10, 20, 30, 255],
]);
const out = erodeImage(img, 1);
for (let i = 0; i < out.data.length; i += 4) {
@@ -133,34 +146,44 @@ describe('image-обёртки', () => {
});
});
describe('strokeImage', () => {
it('кольцо цвета обводки вокруг квадрата', () => {
describe("strokeImage", () => {
it("кольцо цвета обводки вокруг квадрата", () => {
const pixels: number[][] = [];
for (let y = 0; y < 7; y++) {
for (let x = 0; x < 7; x++) {
pixels.push(x >= 2 && x <= 4 && y >= 2 && y <= 4 ? [255, 0, 0, 255] : [0, 0, 0, 0]);
pixels.push(
x >= 2 && x <= 4 && y >= 2 && y <= 4
? [255, 0, 0, 255]
: [0, 0, 0, 0],
);
}
}
const out = strokeImage(makeImage(7, 7, pixels), 1, '#0000ff');
const at = (x: number, y: number) =>
[...out.data.slice((y * 7 + x) * 4, (y * 7 + x) * 4 + 4)];
const out = strokeImage(makeImage(7, 7, pixels), 1, "#0000ff");
const at = (x: number, y: number) => [
...out.data.slice((y * 7 + x) * 4, (y * 7 + x) * 4 + 4),
];
expect(at(2, 3)).toEqual([255, 0, 0, 255]);
expect(at(1, 3)).toEqual([0, 0, 255, 255]);
expect(at(0, 0)).toEqual([0, 0, 0, 0]);
});
});
describe('contourImage', () => {
it('линия по краю квадрата, центр прозрачен', () => {
describe("contourImage", () => {
it("линия по краю квадрата, центр прозрачен", () => {
const pixels: number[][] = [];
for (let y = 0; y < 7; y++) {
for (let x = 0; x < 7; x++) {
pixels.push(x >= 2 && x <= 4 && y >= 2 && y <= 4 ? [255, 0, 0, 255] : [0, 0, 0, 0]);
pixels.push(
x >= 2 && x <= 4 && y >= 2 && y <= 4
? [255, 0, 0, 255]
: [0, 0, 0, 0],
);
}
}
const out = contourImage(makeImage(7, 7, pixels), 1, '#0000ff');
const at = (x: number, y: number) =>
[...out.data.slice((y * 7 + x) * 4, (y * 7 + x) * 4 + 4)];
const out = contourImage(makeImage(7, 7, pixels), 1, "#0000ff");
const at = (x: number, y: number) => [
...out.data.slice((y * 7 + x) * 4, (y * 7 + x) * 4 + 4),
];
expect(at(2, 2)).toEqual([0, 0, 255, 255]);
expect(at(3, 3)).toEqual([0, 0, 0, 0]);
expect(at(1, 3)).toEqual([0, 0, 0, 0]);
+40 -10
View File
@@ -1,5 +1,5 @@
import { parseHex } from './alpha';
import { clonePixelImage, createPixelImage, type PixelImage } from './types';
import { parseHex } from "./alpha";
import { clonePixelImage, createPixelImage, type PixelImage } from "./types";
type Mask = Uint8Array;
@@ -25,7 +25,12 @@ export function buildAlphaMask(img: PixelImage): Mask {
return mask;
}
export function dilateMask(mask: Mask, width: number, height: number, radius: number): Mask {
export function dilateMask(
mask: Mask,
width: number,
height: number,
radius: number,
): Mask {
const r = Math.trunc(radius);
if (r < 1) return mask.slice();
const out = new Uint8Array(mask.length);
@@ -48,7 +53,12 @@ export function dilateMask(mask: Mask, width: number, height: number, radius: nu
return out;
}
export function erodeMask(mask: Mask, width: number, height: number, radius: number): Mask {
export function erodeMask(
mask: Mask,
width: number,
height: number,
radius: number,
): Mask {
const r = Math.trunc(radius);
if (r < 1) return mask.slice();
const out = new Uint8Array(mask.length);
@@ -89,18 +99,24 @@ export function applyMaskAlpha(img: PixelImage, mask: Mask): PixelImage {
export function dilateImage(img: PixelImage, radiusPx: number): PixelImage {
if (radiusPx < 1) return clonePixelImage(img);
return applyMaskAlpha(img, dilateMask(buildAlphaMask(img), img.width, img.height, radiusPx));
return applyMaskAlpha(
img,
dilateMask(buildAlphaMask(img), img.width, img.height, radiusPx),
);
}
export function erodeImage(img: PixelImage, radiusPx: number): PixelImage {
if (radiusPx < 1) return clonePixelImage(img);
return applyMaskAlpha(img, erodeMask(buildAlphaMask(img), img.width, img.height, radiusPx));
return applyMaskAlpha(
img,
erodeMask(buildAlphaMask(img), img.width, img.height, radiusPx),
);
}
export function strokeImage(
img: PixelImage,
radiusPx: number,
colorHex: string
colorHex: string,
): PixelImage {
const r = Math.trunc(radiusPx);
if (r < 1) return clonePixelImage(img);
@@ -125,7 +141,11 @@ export function strokeImage(
return out;
}
export function contourImage(img: PixelImage, radiusPx: number, colorHex: string): PixelImage {
export function contourImage(
img: PixelImage,
radiusPx: number,
colorHex: string,
): PixelImage {
const r = Math.max(1, Math.trunc(radiusPx));
const [cr, cg, cb] = parseHex(colorHex);
const mask = buildAlphaMask(img);
@@ -147,11 +167,21 @@ export function contourImage(img: PixelImage, radiusPx: number, colorHex: string
return out;
}
export function openingMask(mask: Mask, w: number, h: number, radius: number): Mask {
export function openingMask(
mask: Mask,
w: number,
h: number,
radius: number,
): Mask {
return dilateMask(erodeMask(mask, w, h, radius), w, h, radius);
}
export function closingMask(mask: Mask, w: number, h: number, radius: number): Mask {
export function closingMask(
mask: Mask,
w: number,
h: number,
radius: number,
): Mask {
return erodeMask(dilateMask(mask, w, h, radius), w, h, radius);
}
+56 -51
View File
@@ -1,4 +1,4 @@
import { describe, expect, it } from 'vitest';
import { describe, expect, it } from "vitest";
import {
analogousSet,
complementarySet,
@@ -16,60 +16,60 @@ import {
shadeSet,
sortPalette,
triadicSet,
tetradicSet
} from './palette';
tetradicSet,
} from "./palette";
describe('конвертация rgb↔hsl', () => {
it('красный → hsl(0,100%,50%) и обратно', () => {
const hsl = rgbToHsl(hexToRgb('#ff0000'));
describe("конвертация rgb↔hsl", () => {
it("красный → hsl(0,100%,50%) и обратно", () => {
const hsl = rgbToHsl(hexToRgb("#ff0000"));
expect(hsl.h).toBeCloseTo(0, 0);
expect(hsl.s).toBeCloseTo(1, 5);
expect(hsl.l).toBeCloseTo(0.5, 5);
expect(rgbToHex(hslToRgb({ h: 0, s: 1, l: 0.5 }))).toBe('#ff0000');
expect(rgbToHex(hslToRgb({ h: 0, s: 1, l: 0.5 }))).toBe("#ff0000");
});
it('серые не имеют оттенка', () => {
expect(rgbToHsl(hexToRgb('#808080')).s).toBe(0);
it("серые не имеют оттенка", () => {
expect(rgbToHsl(hexToRgb("#808080")).s).toBe(0);
});
it('круговой переход 360° возвращает исходный цвет', () => {
const base = '#3b82f6';
expect(rgbToHex(hslToRgb({ ...rgbToHsl(hexToRgb(base)), h: 720 + 30 }))).toBe(
rgbToHex(hslToRgb({ ...rgbToHsl(hexToRgb(base)), h: 30 }))
);
it("круговой переход 360° возвращает исходный цвет", () => {
const base = "#3b82f6";
expect(
rgbToHex(hslToRgb({ ...rgbToHsl(hexToRgb(base)), h: 720 + 30 })),
).toBe(rgbToHex(hslToRgb({ ...rgbToHsl(hexToRgb(base)), h: 30 })));
});
});
describe('гармонии', () => {
it('complementary — пара с сдвигом 180°', () => {
const [a, b] = complementarySet('#ff0000');
expect(a).toBe('#ff0000');
describe("гармонии", () => {
it("complementary — пара с сдвигом 180°", () => {
const [a, b] = complementarySet("#ff0000");
expect(a).toBe("#ff0000");
const ha = rgbToHsl(hexToRgb(a)).h;
const hb = rgbToHsl(hexToRgb(b)).h;
expect(Math.abs((hb - ha + 360) % 360)).toBeCloseTo(180, 0);
});
it('triadic — три цвета через 120°', () => {
const set = triadicSet('#ff0000');
it("triadic — три цвета через 120°", () => {
const set = triadicSet("#ff0000");
expect(set).toHaveLength(3);
const hues = set.map((h) => rgbToHsl(hexToRgb(h)).h);
expect(hues[1] - hues[0]).toBeCloseTo(120, 0);
expect(hues[2] - hues[0]).toBeCloseTo(240, 0);
});
it('tetradic — четыре цвета через 90°', () => {
const set = tetradicSet('#00ff00');
it("tetradic — четыре цвета через 90°", () => {
const set = tetradicSet("#00ff00");
expect(set).toHaveLength(4);
});
it('analogous симметричен вокруг базы', () => {
const set = analogousSet('#0000ff', 30, 5);
it("analogous симметричен вокруг базы", () => {
const set = analogousSet("#0000ff", 30, 5);
expect(set).toHaveLength(5);
expect(set[2]).toBe(normalizeHex('#0000ff'));
expect(set[2]).toBe(normalizeHex("#0000ff"));
});
it('monochromatic держит оттенок, меняет светлоту', () => {
const set = monochromaticSet('#ff8800', 5, 60);
it("monochromatic держит оттенок, меняет светлоту", () => {
const set = monochromaticSet("#ff8800", 5, 60);
expect(set).toHaveLength(5);
const hues = new Set(set.map((h) => Math.round(rgbToHsl(hexToRgb(h)).h)));
expect(hues.size).toBe(1);
@@ -77,62 +77,67 @@ describe('гармонии', () => {
expect(Math.min(...lights)).toBeLessThan(Math.max(...lights));
});
it('shades — тёмный край темнее базы', () => {
const set = shadeSet('#88cc44', 4, 70);
it("shades — тёмный край темнее базы", () => {
const set = shadeSet("#88cc44", 4, 70);
const lights = set.map((h) => rgbToHsl(hexToRgb(h)).l);
expect(lights[lights.length - 1]).toBeLessThan(lights[0]);
});
});
describe('parseHexList / mixColors / sortPalette', () => {
it('парсит список и отбрасывает мусор и токены без решётки', () => {
expect(parseHexList('#ff0000, #00FF00 ; 00ff00 zz')).toEqual(['#ff0000', '#00ff00']);
describe("parseHexList / mixColors / sortPalette", () => {
it("парсит список и отбрасывает мусор и токены без решётки", () => {
expect(parseHexList("#ff0000, #00FF00 ; 00ff00 zz")).toEqual([
"#ff0000",
"#00ff00",
]);
});
it('пустой валидный список бросает badHex', () => {
expect(() => parseHexList('нет цветов')).toThrow(/errors\.badHex/);
it("пустой валидный список бросает badHex", () => {
expect(() => parseHexList("нет цветов")).toThrow(/errors\.badHex/);
});
it('mixColors — среднее компонент', () => {
expect(mixColors(['#000000', '#ffffff'])).toBe('#808080');
it("mixColors — среднее компонент", () => {
expect(mixColors(["#000000", "#ffffff"])).toBe("#808080");
});
it('sortPalette по luma ставит тёмные раньше', () => {
const sorted = sortPalette(['#ffffff', '#000000', '#808080'], 'luma');
expect(sorted[0]).toBe('#000000');
expect(sorted[2]).toBe('#ffffff');
it("sortPalette по luma ставит тёмные раньше", () => {
const sorted = sortPalette(["#ffffff", "#000000", "#808080"], "luma");
expect(sorted[0]).toBe("#000000");
expect(sorted[2]).toBe("#ffffff");
});
});
describe('рендеры', () => {
it('renderSwatches strip: колонки по цветам', () => {
const img = renderSwatches(['#ff0000', '#00ff00'], 200, 'strip');
describe("рендеры", () => {
it("renderSwatches strip: колонки по цветам", () => {
const img = renderSwatches(["#ff0000", "#00ff00"], 200, "strip");
expect(img.width).toBe(200);
expect(img.data[(Math.floor(img.height / 2) * 200 + 10) * 4 + 3]).toBe(255);
expect(img.data[(Math.floor(img.height / 2) * 200 + 10) * 4]).toBeGreaterThan(200);
expect(
img.data[(Math.floor(img.height / 2) * 200 + 10) * 4],
).toBeGreaterThan(200);
const right = (Math.floor(img.height / 2) * 200 + 150) * 4;
expect(img.data[right]).toBeLessThan(50);
expect(img.data[right + 1]).toBeGreaterThan(200);
});
it('renderSwatches grid: квадратные ячейки', () => {
const img = renderSwatches(['#111111', '#222222', '#333333'], 120, 'grid');
it("renderSwatches grid: квадратные ячейки", () => {
const img = renderSwatches(["#111111", "#222222", "#333333"], 120, "grid");
expect(img.width).toBe(120);
expect(img.height).toBeGreaterThan(0);
});
it('renderWheel: углы прозрачны, центр непрозрачен', () => {
it("renderWheel: углы прозрачны, центр непрозрачен", () => {
const size = 101;
const img = renderWheel(size, 50);
expect(img.data[3]).toBe(0);
const c = ((Math.floor(size / 2) * size) + Math.floor(size / 2)) * 4;
const c = (Math.floor(size / 2) * size + Math.floor(size / 2)) * 4;
expect(img.data[c + 3]).toBe(255);
});
it('renderBlend: левый край = a, правый = b', () => {
const img = renderBlend('#000000', '#ffffff', 100);
it("renderBlend: левый край = a, правый = b", () => {
const img = renderBlend("#000000", "#ffffff", 100);
expect(img.data[0]).toBe(0);
const last = (99 * 4);
const last = 99 * 4;
expect(img.data[last]).toBe(255);
});
});
+79 -28
View File
@@ -1,25 +1,25 @@
import { ToolError } from './errors';
import type { PixelImage } from './types';
import { createPixelImage } from './types';
import { ToolError } from "./errors";
import type { PixelImage } from "./types";
import { createPixelImage } from "./types";
export type Rgb = { r: number; g: number; b: number };
export type Hsl = { h: number; s: number; l: number };
export function hexToRgb(hex: string): Rgb {
const m = /^#([0-9a-f]{6})$/i.exec(hex.trim());
if (!m) throw new ToolError('errors.badHex', { value: hex });
if (!m) throw new ToolError("errors.badHex", { value: hex });
const d = m[1];
return {
r: parseInt(d.slice(0, 2), 16),
g: parseInt(d.slice(2, 4), 16),
b: parseInt(d.slice(4, 6), 16)
b: parseInt(d.slice(4, 6), 16),
};
}
const byte = (v: number) =>
Math.round(Math.min(255, Math.max(0, v)))
.toString(16)
.padStart(2, '0');
.padStart(2, "0");
export function rgbToHex({ r, g, b }: Rgb): string {
return `#${byte(r)}${byte(g)}${byte(b)}`;
@@ -60,7 +60,7 @@ export function hslToRgb({ h, s, l }: Hsl): Rgb {
return {
r: Math.round((r + m) * 255),
g: Math.round((g + m) * 255),
b: Math.round((b + m) * 255)
b: Math.round((b + m) * 255),
};
}
@@ -82,16 +82,31 @@ export function triadicSet(base: string): string[] {
}
export function tetradicSet(base: string): string[] {
return [normalizeHex(base), shiftHue(base, 90), shiftHue(base, 180), shiftHue(base, 270)];
return [
normalizeHex(base),
shiftHue(base, 90),
shiftHue(base, 180),
shiftHue(base, 270),
];
}
export function analogousSet(base: string, spreadDeg: number, count: number): string[] {
export function analogousSet(
base: string,
spreadDeg: number,
count: number,
): string[] {
const n = Math.max(3, Math.min(9, Math.round(count)));
const half = Math.floor(n / 2);
return Array.from({ length: n }, (_, i) => shiftHue(base, (i - half) * spreadDeg));
return Array.from({ length: n }, (_, i) =>
shiftHue(base, (i - half) * spreadDeg),
);
}
export function monochromaticSet(base: string, count: number, rangePercent: number): string[] {
export function monochromaticSet(
base: string,
count: number,
rangePercent: number,
): string[] {
const n = Math.max(2, Math.min(9, Math.round(count)));
const baseL = rgbToHsl(hexToRgb(normalizeHex(base))).l;
const halfSpan = Math.min(0.495, rangePercent / 200);
@@ -102,7 +117,11 @@ export function monochromaticSet(base: string, count: number, rangePercent: numb
});
}
export function shadeSet(base: string, count: number, depthPercent: number): string[] {
export function shadeSet(
base: string,
count: number,
depthPercent: number,
): string[] {
const n = Math.max(2, Math.min(9, Math.round(count)));
const baseL = rgbToHsl(hexToRgb(normalizeHex(base))).l;
const floorL = Math.max(0.03, baseL - depthPercent / 100);
@@ -118,24 +137,28 @@ export function parseHexList(text: string): string[] {
.map((t) => t.trim())
.filter((t) => /^#[0-9a-f]{6}$/i.test(t))
.map((t) => normalizeHex(t));
if (list.length === 0) throw new ToolError('errors.badHex', { value: text });
if (list.length === 0) throw new ToolError("errors.badHex", { value: text });
return list;
}
export function normalizeHex(hex: string): string {
const m = /^#([0-9a-f]{6})$/i.exec(hex.trim());
if (!m) throw new ToolError('errors.badHex', { value: hex });
if (!m) throw new ToolError("errors.badHex", { value: hex });
return `#${m[1].toLowerCase()}`;
}
export function mixColors(hexes: string[]): string {
const sum = hexes
.map(hexToRgb)
.reduce((acc, c) => ({ r: acc.r + c.r, g: acc.g + c.g, b: acc.b + c.b }), { r: 0, g: 0, b: 0 });
.reduce((acc, c) => ({ r: acc.r + c.r, g: acc.g + c.g, b: acc.b + c.b }), {
r: 0,
g: 0,
b: 0,
});
return rgbToHex({
r: sum.r / hexes.length,
g: sum.g / hexes.length,
b: sum.b / hexes.length
b: sum.b / hexes.length,
});
}
@@ -144,15 +167,17 @@ export function luma(hex: string): number {
return 0.2126 * r + 0.7152 * g + 0.0722 * b;
}
export type SortKey = 'hue' | 'luma' | 'sat';
export type SortKey = "hue" | "luma" | "sat";
export function sortPalette(hexes: string[], key: SortKey): string[] {
const scored = hexes.map((h) => {
if (key === 'luma') return { h, k: luma(h) };
if (key === "luma") return { h, k: luma(h) };
const hsl = rgbToHsl(hexToRgb(h));
return { h, k: key === 'hue' ? hsl.h : hsl.s };
return { h, k: key === "hue" ? hsl.h : hsl.s };
});
return scored.sort((a, b) => a.k - b.k || a.h.localeCompare(b.h)).map((s) => s.h);
return scored
.sort((a, b) => a.k - b.k || a.h.localeCompare(b.h))
.map((s) => s.h);
}
function clamp01(v: number): number {
@@ -160,15 +185,28 @@ function clamp01(v: number): number {
}
/** Горизонтальные равные колонки-свотчи (strip) или сетка ~квадратных ячеек (grid). */
export function renderSwatches(colors: string[], width: number, layout: 'strip' | 'grid'): PixelImage {
export function renderSwatches(
colors: string[],
width: number,
layout: "strip" | "grid",
): PixelImage {
const n = colors.length;
if (layout === 'strip') {
if (layout === "strip") {
const cellW = width / n;
const height = Math.max(24, Math.round(cellW));
const out = createPixelImage(width, height);
colors.forEach((hex, i) => {
const { r, g, b } = hexToRgb(hex);
fillRect(out, Math.floor(i * cellW), 0, Math.ceil(cellW), height, r, g, b);
fillRect(
out,
Math.floor(i * cellW),
0,
Math.ceil(cellW),
height,
r,
g,
b,
);
});
return out;
}
@@ -179,7 +217,16 @@ export function renderSwatches(colors: string[], width: number, layout: 'strip'
const out = createPixelImage(width, height);
colors.forEach((hex, i) => {
const { r, g, b } = hexToRgb(hex);
fillRect(out, (i % cols) * cell, Math.floor(i / cols) * cell, cell, cell, r, g, b);
fillRect(
out,
(i % cols) * cell,
Math.floor(i / cols) * cell,
cell,
cell,
r,
g,
b,
);
});
return out;
}
@@ -222,13 +269,17 @@ export function renderBlend(a: string, b: string, width: number): PixelImage {
height,
Math.round(ca.r + (cb.r - ca.r) * t),
Math.round(ca.g + (cb.g - ca.g) * t),
Math.round(ca.b + (cb.b - ca.b) * t)
Math.round(ca.b + (cb.b - ca.b) * t),
);
}
return out;
}
export function stepColors(aHex: string, bHex: string, steps: number): string[] {
export function stepColors(
aHex: string,
bHex: string,
steps: number,
): string[] {
const n = Math.max(2, Math.min(12, Math.round(steps)));
const ca = hexToRgb(aHex);
const cb = hexToRgb(bHex);
@@ -237,7 +288,7 @@ export function stepColors(aHex: string, bHex: string, steps: number): string[]
return rgbToHex({
r: ca.r + (cb.r - ca.r) * t,
g: ca.g + (cb.g - ca.g) * t,
b: ca.b + (cb.b - ca.b) * t
b: ca.b + (cb.b - ca.b) * t,
});
});
}
@@ -250,7 +301,7 @@ function fillRect(
h: number,
r: number,
g: number,
b: number
b: number,
): void {
for (let y = y0; y < Math.min(y0 + h, img.height); y++) {
for (let x = x0; x < Math.min(x0 + w, img.width); x++) {
+41 -33
View File
@@ -1,63 +1,71 @@
import { describe, expect, it } from 'vitest';
import { addNoise, defringe, featherAlpha, mulberry32, pixelate, shuffleBlocks, silhouette } from './pixel-fx';
import { makeImage } from './test-helpers';
import { describe, expect, it } from "vitest";
import {
addNoise,
defringe,
featherAlpha,
mulberry32,
pixelate,
shuffleBlocks,
silhouette,
} from "./pixel-fx";
import { makeImage } from "./test-helpers";
describe('pixelate', () => {
it('блок усредняется: шахматка 2×2 с блоком 2 → один цвет', () => {
describe("pixelate", () => {
it("блок усредняется: шахматка 2×2 с блоком 2 → один цвет", () => {
const img = makeImage(2, 2, [
[0, 0, 0, 255],
[200, 200, 200, 255],
[100, 100, 100, 255],
[140, 140, 140, 255]
[140, 140, 140, 255],
]);
const out = pixelate(img, 2);
expect(out.data[0]).toBeCloseTo(110, 0);
expect(out.data[4]).toBeCloseTo(110, 0);
});
it('однотонное изображение не меняется', () => {
it("однотонное изображение не меняется", () => {
const img = makeImage(3, 3, new Array(9).fill([50, 60, 70, 255]));
expect([...pixelate(img, 2).data]).toEqual([...img.data]);
});
});
describe('shuffleBlocks / addNoise — детерминизм по seed', () => {
it('тот же seed даёт то же перемешивание', () => {
describe("shuffleBlocks / addNoise — детерминизм по seed", () => {
it("тот же seed даёт то же перемешивание", () => {
const img = makeImage(4, 1, [
[10, 0, 0, 255],
[20, 0, 0, 255],
[30, 0, 0, 255],
[40, 0, 0, 255]
[40, 0, 0, 255],
]);
const a = shuffleBlocks(img, 1, 7);
const b = shuffleBlocks(img, 1, 7);
expect([...a.data]).toEqual([...b.data]);
});
it('мультимножество пикселей сохраняется (перестановка)', () => {
it("мультимножество пикселей сохраняется (перестановка)", () => {
const img = makeImage(4, 1, [
[10, 0, 0, 255],
[20, 0, 0, 255],
[30, 0, 0, 255],
[40, 0, 0, 255]
[40, 0, 0, 255],
]);
const out = [...shuffleBlocks(img, 1, 99).data.filter((_, i) => i % 4 === 0)].sort(
(x, y) => x - y
);
const out = [
...shuffleBlocks(img, 1, 99).data.filter((_, i) => i % 4 === 0),
].sort((x, y) => x - y);
expect(out).toEqual([10, 20, 30, 40]);
});
it('addNoise при том же seed воспроизводим, amount=0 — идентичность', () => {
it("addNoise при том же seed воспроизводим, amount=0 — идентичность", () => {
const img = makeImage(2, 2, new Array(4).fill([128, 64, 32, 255]));
const a = addNoise(img, 20, 'mono', 5);
const b = addNoise(img, 20, 'mono', 5);
const a = addNoise(img, 20, "mono", 5);
const b = addNoise(img, 20, "mono", 5);
expect([...a.data]).toEqual([...b.data]);
expect([...addNoise(img, 0, 'mono', 999).data]).toEqual([...img.data]);
expect([...addNoise(img, 0, "mono", 999).data]).toEqual([...img.data]);
});
});
describe('featherAlpha', () => {
it('жёсткий край получает промежуточные альфы', () => {
describe("featherAlpha", () => {
it("жёсткий край получает промежуточные альфы", () => {
// левая половина непрозрачная, правая прозрачная
const img = makeImage(6, 1, [
[255, 0, 0, 255],
@@ -65,7 +73,7 @@ describe('featherAlpha', () => {
[255, 0, 0, 255],
[255, 0, 0, 0],
[255, 0, 0, 0],
[255, 0, 0, 0]
[255, 0, 0, 0],
]);
const out = featherAlpha(img, 1);
const alphas = [0, 1, 2].map((x) => out.data[x * 4 + 3]);
@@ -74,11 +82,11 @@ describe('featherAlpha', () => {
});
});
describe('defringe', () => {
it('полупрозрачному пикселю берётся RGB от соседнего непрозрачного', () => {
describe("defringe", () => {
it("полупрозрачному пикселю берётся RGB от соседнего непрозрачного", () => {
const img = makeImage(2, 1, [
[250, 250, 250, 255],
[255, 0, 0, 128]
[255, 0, 0, 128],
]);
const out = defringe(img, 2);
expect(out.data[4]).toBe(250);
@@ -86,30 +94,30 @@ describe('defringe', () => {
expect(out.data[7]).toBe(128); // альфа сохранена
});
it('полностью прозрачные области не трогаются', () => {
it("полностью прозрачные области не трогаются", () => {
const img = makeImage(2, 1, [
[250, 250, 250, 255],
[0, 0, 0, 0]
[0, 0, 0, 0],
]);
const out = defringe(img, 2);
expect(out.data[4 + 3]).toBe(0);
});
});
describe('silhouette', () => {
it('видимые пиксели заливаются цветом, ниже порога — прозрачность', () => {
describe("silhouette", () => {
it("видимые пиксели заливаются цветом, ниже порога — прозрачность", () => {
const img = makeImage(2, 1, [
[123, 45, 67, 255],
[123, 45, 67, 10]
[123, 45, 67, 10],
]);
const out = silhouette(img, '#00ff00', 50);
const out = silhouette(img, "#00ff00", 50);
expect([...out.data.slice(0, 4)]).toEqual([0, 255, 0, 255]);
expect(out.data[4 + 3]).toBe(0);
});
});
describe('mulberry32', () => {
it('последовательность детерминирована', () => {
describe("mulberry32", () => {
it("последовательность детерминирована", () => {
const a = mulberry32(42);
const b = mulberry32(42);
expect([a(), a(), a()]).toEqual([b(), b(), b()]);
+25 -12
View File
@@ -1,7 +1,7 @@
import { hexToRgb } from './palette';
import type { PixelImage } from './types';
import { createPixelImage } from './types';
import { gaussianBlur } from './convolution';
import { hexToRgb } from "./palette";
import type { PixelImage } from "./types";
import { createPixelImage } from "./types";
import { gaussianBlur } from "./convolution";
/** Детерминированный ГПСЧ (mulberry32): одинаковый seed — одинаковый результат. */
export function mulberry32(seed: number): () => number {
@@ -59,7 +59,11 @@ export function pixelate(img: PixelImage, blockSize: number): PixelImage {
}
/** Перемешивает блоки blockSize×Blocksize между собой детерминированно по seed. */
export function shuffleBlocks(img: PixelImage, blockSize: number, seed: number): PixelImage {
export function shuffleBlocks(
img: PixelImage,
blockSize: number,
seed: number,
): PixelImage {
const bs = Math.max(1, Math.round(blockSize));
const cols = Math.ceil(img.width / bs);
const rows = Math.ceil(img.height / bs);
@@ -92,28 +96,32 @@ export function shuffleBlocks(img: PixelImage, blockSize: number, seed: number):
return out;
}
export type NoiseMode = 'mono' | 'color';
export type NoiseMode = "mono" | "color";
/** Зерно: amountPercent — сила отклонения от оригинала. Детерминировано по seed. */
export function addNoise(
img: PixelImage,
amountPercent: number,
mode: NoiseMode,
seed: number
seed: number,
): PixelImage {
const out = createPixelImage(img.width, img.height);
const amount = Math.min(Math.max(amountPercent, 0), 100) / 100;
const rng = mulberry32(seed);
for (let i = 0; i < img.data.length; i += 4) {
const shift = (rng() * 2 - 1) * amount * 255;
if (mode === 'mono') {
if (mode === "mono") {
out.data[i] = clampByte(img.data[i] + shift);
out.data[i + 1] = clampByte(img.data[i + 1] + shift);
out.data[i + 2] = clampByte(img.data[i + 2] + shift);
} else {
out.data[i] = clampByte(img.data[i] + (rng() * 2 - 1) * amount * 255);
out.data[i + 1] = clampByte(img.data[i + 1] + (rng() * 2 - 1) * amount * 255);
out.data[i + 2] = clampByte(img.data[i + 2] + (rng() * 2 - 1) * amount * 255);
out.data[i + 1] = clampByte(
img.data[i + 1] + (rng() * 2 - 1) * amount * 255,
);
out.data[i + 2] = clampByte(
img.data[i + 2] + (rng() * 2 - 1) * amount * 255,
);
}
out.data[i + 3] = img.data[i + 3];
}
@@ -160,7 +168,8 @@ export function defringe(img: PixelImage, radius: number): PixelImage {
if (Math.max(Math.abs(dx), Math.abs(dy)) !== ry) continue;
const nx = x + dx;
const ny = y + dy;
if (nx < 0 || ny < 0 || nx >= img.width || ny >= img.height) continue;
if (nx < 0 || ny < 0 || nx >= img.width || ny >= img.height)
continue;
const si = (ny * img.width + nx) * 4;
if (img.data[si + 3] !== 255) continue;
out.data[di] = img.data[si];
@@ -176,7 +185,11 @@ export function defringe(img: PixelImage, radius: number): PixelImage {
}
/** Силуэт: все видимые пиксели заливаются одним цветом, альфа сохраняется. */
export function silhouette(img: PixelImage, colorHex: string, alphaThreshold: number): PixelImage {
export function silhouette(
img: PixelImage,
colorHex: string,
alphaThreshold: number,
): PixelImage {
const out = createPixelImage(img.width, img.height);
const { r, g, b } = hexToRgb(colorHex);
for (let i = 0; i < img.data.length; i += 4) {
+28 -23
View File
@@ -1,37 +1,42 @@
import { describe, expect, it } from 'vitest';
import { ditherImage, mapToNearest, medianCutPalette, quantizeImage } from './quantize';
import { makeImage } from './test-helpers';
import { describe, expect, it } from "vitest";
import {
ditherImage,
mapToNearest,
medianCutPalette,
quantizeImage,
} from "./quantize";
import { makeImage } from "./test-helpers";
describe('medianCutPalette', () => {
it('два явных кластера при k=2 дают сами цвета', () => {
describe("medianCutPalette", () => {
it("два явных кластера при k=2 дают сами цвета", () => {
const img = makeImage(4, 1, [
[0, 0, 0, 255],
[0, 0, 0, 255],
[255, 255, 255, 255],
[255, 255, 255, 255]
[255, 255, 255, 255],
]);
const palette = medianCutPalette(img, 2);
expect(palette).toHaveLength(2);
const hexes = palette.map((c) => `${c.r},${c.g},${c.b}`).sort();
expect(hexes).toEqual(['0,0,0', '255,255,255']);
expect(hexes).toEqual(["0,0,0", "255,255,255"]);
});
it('пустое изображение даёт чёрную заглушку', () => {
it("пустое изображение даёт чёрную заглушку", () => {
const empty = makeImage(2, 2, new Array(4).fill([0, 0, 0, 0]));
expect(medianCutPalette(empty, 4)).toHaveLength(1);
});
});
describe('quantizeImage / ditherImage', () => {
it('квантование укладывает пиксели в палитру, прозрачность сохраняется', () => {
describe("quantizeImage / ditherImage", () => {
it("квантование укладывает пиксели в палитру, прозрачность сохраняется", () => {
const img = makeImage(3, 1, [
[10, 10, 10, 255],
[250, 250, 250, 255],
[0, 0, 0, 0]
[0, 0, 0, 0],
]);
const { image, palette } = quantizeImage(img, 2);
expect(palette.length).toBeLessThanOrEqual(2);
expect(image.data[(2) * 4 + 3]).toBe(0); // прозрачный остался
expect(image.data[2 * 4 + 3]).toBe(0); // прозрачный остался
for (let x = 0; x < 2; x++) {
const i = x * 4;
const matched = palette.some((hex) => {
@@ -42,9 +47,9 @@ describe('quantizeImage / ditherImage', () => {
}
});
it('floyd-steinberg расщепляет серый 50% на чёрное и белое', () => {
it("floyd-steinberg расщепляет серый 50% на чёрное и белое", () => {
const gray = makeImage(16, 16, new Array(256).fill([128, 128, 128, 255]));
const out = ditherImage(gray, 2, 'floyd-steinberg', ['#000000', '#ffffff']);
const out = ditherImage(gray, 2, "floyd-steinberg", ["#000000", "#ffffff"]);
let hasDark = false;
let hasLight = false;
for (let i = 0; i < out.data.length; i += 4) {
@@ -55,27 +60,27 @@ describe('quantizeImage / ditherImage', () => {
expect(hasLight).toBe(true);
});
it('bayer детерминирован', () => {
it("bayer детерминирован", () => {
const gray = makeImage(8, 8, new Array(64).fill([128, 128, 128, 255]));
const a = ditherImage(gray, 2, 'bayer');
const b = ditherImage(gray, 2, 'bayer');
const a = ditherImage(gray, 2, "bayer");
const b = ditherImage(gray, 2, "bayer");
expect([...a.data]).toEqual([...b.data]);
});
it('полностью прозрачное изображение не падает', () => {
it("полностью прозрачное изображение не падает", () => {
const empty = makeImage(2, 2, new Array(4).fill([0, 0, 0, 0]));
const out = ditherImage(empty, 4, 'bayer');
const out = ditherImage(empty, 4, "bayer");
expect(out.data[3]).toBe(0);
});
});
describe('mapToNearest', () => {
it('маппинг на ближайший из списка', () => {
describe("mapToNearest", () => {
it("маппинг на ближайший из списка", () => {
const img = makeImage(2, 1, [
[10, 10, 10, 255],
[240, 240, 240, 255]
[240, 240, 240, 255],
]);
const out = mapToNearest(img, ['#000000', '#ffffff']);
const out = mapToNearest(img, ["#000000", "#ffffff"]);
expect(out.data[0]).toBe(0);
expect(out.data[4]).toBe(255);
});
+30 -17
View File
@@ -1,7 +1,7 @@
import type { PixelImage } from './types';
import { createPixelImage } from './types';
import { rgbToHex } from './palette';
import { hexToRgb } from './palette';
import type { PixelImage } from "./types";
import { createPixelImage } from "./types";
import { rgbToHex } from "./palette";
import { hexToRgb } from "./palette";
type Rgb = { r: number; g: number; b: number };
@@ -73,9 +73,9 @@ export function medianCutPalette(img: PixelImage, k: number): Rgb[] {
const bucket = buckets[targetIdx];
const ranges = [
{ ch: 'r' as const, range: bucket.max.r - bucket.min.r },
{ ch: 'g' as const, range: bucket.max.g - bucket.min.g },
{ ch: 'b' as const, range: bucket.max.b - bucket.min.b }
{ ch: "r" as const, range: bucket.max.r - bucket.min.r },
{ ch: "g" as const, range: bucket.max.g - bucket.min.g },
{ ch: "b" as const, range: bucket.max.b - bucket.min.b },
].sort((a, b) => b.range - a.range);
const widest = ranges[0].ch;
bucket.px.sort((a, b) => a[widest] - b[widest]);
@@ -84,7 +84,7 @@ export function medianCutPalette(img: PixelImage, k: number): Rgb[] {
...buckets.slice(0, targetIdx),
makeBucket(bucket.px.slice(0, mid)),
makeBucket(bucket.px.slice(mid)),
...buckets.slice(targetIdx + 1)
...buckets.slice(targetIdx + 1),
];
}
@@ -93,7 +93,7 @@ export function medianCutPalette(img: PixelImage, k: number): Rgb[] {
.map((b) => ({
r: Math.round(b.px.reduce((s, c) => s + c.r, 0) / b.px.length),
g: Math.round(b.px.reduce((s, c) => s + c.g, 0) / b.px.length),
b: Math.round(b.px.reduce((s, c) => s + c.b, 0) / b.px.length)
b: Math.round(b.px.reduce((s, c) => s + c.b, 0) / b.px.length),
}));
}
@@ -109,7 +109,12 @@ export function quantizeImage(img: PixelImage, k: number): QuantizeResult {
for (let i = 0; i < img.data.length; i += 4) {
out.data[i + 3] = img.data[i + 3];
if (img.data[i + 3] === 0) continue;
const chosen = nearestIndex(palette, img.data[i], img.data[i + 1], img.data[i + 2]);
const chosen = nearestIndex(
palette,
img.data[i],
img.data[i + 1],
img.data[i + 2],
);
out.data[i] = palette[chosen].r;
out.data[i + 1] = palette[chosen].g;
out.data[i + 2] = palette[chosen].b;
@@ -118,13 +123,21 @@ export function quantizeImage(img: PixelImage, k: number): QuantizeResult {
}
/** Маппинг каждого пикселя на ближайший цвет пользовательского списка. */
export function mapToNearest(img: PixelImage, paletteHexes: string[]): PixelImage {
export function mapToNearest(
img: PixelImage,
paletteHexes: string[],
): PixelImage {
const palette = paletteHexes.map(hexToRgb);
const out = createPixelImage(img.width, img.height);
for (let i = 0; i < img.data.length; i += 4) {
out.data[i + 3] = img.data[i + 3];
if (img.data[i + 3] === 0) continue;
const chosen = nearestIndex(palette, img.data[i], img.data[i + 1], img.data[i + 2]);
const chosen = nearestIndex(
palette,
img.data[i],
img.data[i + 1],
img.data[i + 2],
);
out.data[i] = palette[chosen].r;
out.data[i + 1] = palette[chosen].g;
out.data[i + 2] = palette[chosen].b;
@@ -136,10 +149,10 @@ const BAYER_4 = [
[0, 8, 2, 10],
[12, 4, 14, 6],
[3, 11, 1, 9],
[15, 7, 13, 5]
[15, 7, 13, 5],
];
export type DitherPattern = 'floyd-steinberg' | 'bayer';
export type DitherPattern = "floyd-steinberg" | "bayer";
/**
* Дизеринг к палитре из k цветов (median-cut) или к явно заданному списку hex.
@@ -149,7 +162,7 @@ export function ditherImage(
img: PixelImage,
k: number,
pattern: DitherPattern,
forcedPaletteHexes?: string[]
forcedPaletteHexes?: string[],
): PixelImage {
const palette = forcedPaletteHexes
? forcedPaletteHexes.map(hexToRgb)
@@ -177,7 +190,7 @@ export function ditherImage(
let g = buf[p * 3 + 1];
let b = buf[p * 3 + 2];
if (pattern === 'bayer') {
if (pattern === "bayer") {
const offset = ((BAYER_4[y % 4][x % 4] + 0.5) / 16 - 0.5) * spread;
r += offset;
g += offset;
@@ -189,7 +202,7 @@ export function ditherImage(
out.data[di + 1] = palette[chosen].g;
out.data[di + 2] = palette[chosen].b;
if (pattern !== 'floyd-steinberg') continue;
if (pattern !== "floyd-steinberg") continue;
const er = r - palette[chosen].r;
const eg = g - palette[chosen].g;
const eb = b - palette[chosen].b;
+21 -14
View File
@@ -1,9 +1,9 @@
import { describe, expect, it } from 'vitest';
import { boxTest, circleTest, renderShape, starTest, wavyTest } from './shapes';
import { makeImage } from './test-helpers';
import { describe, expect, it } from "vitest";
import { boxTest, circleTest, renderShape, starTest, wavyTest } from "./shapes";
import { makeImage } from "./test-helpers";
describe('тесты фигур', () => {
it('круг: центр внутри, угол снаружи', () => {
describe("тесты фигур", () => {
it("круг: центр внутри, угол снаружи", () => {
const t = circleTest(0.5);
expect(t(0, 0)).toBe(true);
expect(t(0.49, 0)).toBe(true);
@@ -11,21 +11,23 @@ describe('тесты фигур', () => {
expect(t(0.4, 0.4)).toBe(false);
});
it('прямоугольник: полуоси независимы', () => {
it("прямоугольник: полуоси независимы", () => {
const t = boxTest(0.5, 0.25);
expect(t(0.45, 0.2)).toBe(true);
expect(t(0.2, 0.3)).toBe(false);
});
it('звезда: луч внутри дальше впадины', () => {
it("звезда: луч внутри дальше впадины", () => {
const t = starTest(5, 0.5, 1, 0);
expect(t(0.9, 0)).toBe(true); // вдоль луча (θ=0)
const valleyAngle = Math.PI / 5; // середина между лучами
expect(t(Math.cos(valleyAngle) * 0.8, Math.sin(valleyAngle) * 0.8)).toBe(false);
expect(t(Math.cos(valleyAngle) * 0.8, Math.sin(valleyAngle) * 0.8)).toBe(
false,
);
expect(t(0.4, 0)).toBe(true); // радиус впадин 0.5 — 0.4 внутри всегда
});
it('волна: фаза двигает границу', () => {
it("волна: фаза двигает границу", () => {
const a = wavyTest(0.5, 0.1, 6, 0);
const b = wavyTest(0.5, 0.1, 6, 180);
const deg = 15; // sin(6·15°)=1 → край 0.6; при фазе 180° край 0.4
@@ -36,19 +38,24 @@ describe('тесты фигур', () => {
});
});
describe('renderShape', () => {
describe("renderShape", () => {
const img = makeImage(4, 2, new Array(8).fill([255, 255, 255, 255]));
it('внутри сохраняет пиксели, снаружи альфа 0', () => {
it("внутри сохраняет пиксели, снаружи альфа 0", () => {
const out = renderShape(img, boxTest(0.5, 0.5));
let opaque = 0;
for (let i = 3; i < out.data.length; i += 4) if (out.data[i] === 255) opaque++;
for (let i = 3; i < out.data.length; i += 4)
if (out.data[i] === 255) opaque++;
expect(opaque).toBe(4);
expect(out.data[4]).toBe(255); // RGB внутри фигуры сохранён
});
it('смещение центра переносит маску', () => {
const shifted = renderShape(makeImage(2, 2, new Array(4).fill([255, 255, 255, 255])), circleTest(0.7), 0.5);
it("смещение центра переносит маску", () => {
const shifted = renderShape(
makeImage(2, 2, new Array(4).fill([255, 255, 255, 255])),
circleTest(0.7),
0.5,
);
expect(shifted.data[3]).toBe(0);
expect(shifted.data[4 + 3]).toBe(255);
});
+5 -5
View File
@@ -1,5 +1,5 @@
import type { PixelImage } from './types';
import { createPixelImage } from './types';
import type { PixelImage } from "./types";
import { createPixelImage } from "./types";
export type ShapeTest = (nx: number, ny: number) => boolean;
@@ -21,7 +21,7 @@ export function starTest(
points: number,
innerFrac: number,
outerFrac: number,
rotationDeg: number
rotationDeg: number,
): ShapeTest {
const n = Math.max(3, Math.round(points));
const rot = (rotationDeg * Math.PI) / 180;
@@ -41,7 +41,7 @@ export function wavyTest(
baseFrac: number,
amplitudeFrac: number,
waves: number,
phaseDeg: number
phaseDeg: number,
): ShapeTest {
const phase = (phaseDeg * Math.PI) / 180;
return (nx, ny) => {
@@ -60,7 +60,7 @@ export function renderShape(
img: PixelImage,
test: ShapeTest,
offsetXFrac = 0,
offsetYFrac = 0
offsetYFrac = 0,
): PixelImage {
const out = createPixelImage(img.width, img.height);
const minDim = Math.min(img.width, img.height);
+14 -5
View File
@@ -1,14 +1,23 @@
import { expect } from 'vitest';
import type { PixelImage } from './types';
import { expect } from "vitest";
import type { PixelImage } from "./types";
export function makeImage(width: number, height: number, pixels: number[][]): PixelImage {
export function makeImage(
width: number,
height: number,
pixels: number[][],
): PixelImage {
const data = new Uint8ClampedArray(pixels.flat());
if (data.length !== width * height * 4) {
throw new Error(`Fixture mismatch: ${data.length} байт на ${width}x${height}`);
throw new Error(
`Fixture mismatch: ${data.length} байт на ${width}x${height}`,
);
}
return { width, height, data };
}
export function expectImageEqual(actual: PixelImage, expectedPixels: number[][]): void {
export function expectImageEqual(
actual: PixelImage,
expectedPixels: number[][],
): void {
expect([...actual.data]).toEqual(expectedPixels.flat());
}
+18 -20
View File
@@ -1,47 +1,45 @@
import { describe, expect, it } from 'vitest';
import { hexToPixels, pixelsToHex } from './text';
import { makeImage } from './test-helpers';
import { describe, expect, it } from "vitest";
import { hexToPixels, pixelsToHex } from "./text";
import { makeImage } from "./test-helpers";
describe('pixelsToHex', () => {
it('форматирует пиксели как rrggbbaa построчно', () => {
describe("pixelsToHex", () => {
it("форматирует пиксели как rrggbbaa построчно", () => {
const out = pixelsToHex(
makeImage(2, 2, [
[255, 0, 0, 255],
[0, 255, 0, 200],
[16, 32, 48, 64],
[0, 0, 0, 0]
])
[0, 0, 0, 0],
]),
);
expect(out).toBe('ff0000ff 00ff00c8\n10203040 00000000');
expect(out).toBe("ff0000ff 00ff00c8\n10203040 00000000");
});
});
describe('hexToPixels', () => {
it('обратим к pixelsToHex', () => {
describe("hexToPixels", () => {
it("обратим к pixelsToHex", () => {
const source = makeImage(3, 1, [
[1, 2, 3, 4],
[250, 251, 252, 253],
[9, 9, 9, 128]
[9, 9, 9, 128],
]);
expect(hexToPixels(pixelsToHex(source), 3)).toEqual(source);
});
it('допускает произвольные переводы строк и регистр', () => {
const out = hexToPixels('FF0000FF\n\n00FF0080 00000080', 1);
it("допускает произвольные переводы строк и регистр", () => {
const out = hexToPixels("FF0000FF\n\n00FF0080 00000080", 1);
expect(out.width).toBe(1);
expect(out.height).toBe(3);
expect([...out.data]).toEqual([
255, 0, 0, 255,
0, 255, 0, 128,
0, 0, 0, 128
255, 0, 0, 255, 0, 255, 0, 128, 0, 0, 0, 128,
]);
});
it.each([
['ff0000', 'битые токены'],
['ff0000ff ff0000ff ff0000ff', 'не делится на ширину'],
['', 'пустой ввод']
])('бросает понятную ошибку: %s (%s)', (input) => {
["ff0000", "битые токены"],
["ff0000ff ff0000ff ff0000ff", "не делится на ширину"],
["", "пустой ввод"],
])("бросает понятную ошибку: %s (%s)", (input) => {
expect(() => hexToPixels(input, 2)).toThrow();
});
});
+22 -14
View File
@@ -1,5 +1,5 @@
import type { PixelImage } from './types';
import { ToolError } from './errors';
import type { PixelImage } from "./types";
import { ToolError } from "./errors";
export function pixelsToHex(img: PixelImage): string {
const rows: string[] = [];
@@ -7,30 +7,38 @@ export function pixelsToHex(img: PixelImage): string {
const parts: string[] = [];
for (let x = 0; x < img.width; x++) {
const i = (y * img.width + x) * 4;
parts.push(byteHex(img.data[i]) + byteHex(img.data[i + 1]) + byteHex(img.data[i + 2]) + byteHex(img.data[i + 3]));
parts.push(
byteHex(img.data[i]) +
byteHex(img.data[i + 1]) +
byteHex(img.data[i + 2]) +
byteHex(img.data[i + 3]),
);
}
rows.push(parts.join(' '));
rows.push(parts.join(" "));
}
return rows.join('\n');
return rows.join("\n");
}
export function hexToPixels(text: string, width: number): PixelImage {
if (!Number.isInteger(width) || width < 1) {
throw new ToolError('errors.widthInt');
throw new ToolError("errors.widthInt");
}
const tokens = text.trim().split(/\s+/).filter((t) => t.length > 0);
const tokens = text
.trim()
.split(/\s+/)
.filter((t) => t.length > 0);
if (tokens.length === 0) {
throw new ToolError('errors.noHexPixels');
throw new ToolError("errors.noHexPixels");
}
if (tokens.some((t) => !/^[0-9a-fA-F]{8}$/.test(t))) {
throw new ToolError('errors.badPixelToken');
throw new ToolError("errors.badPixelToken");
}
const height = tokens.length / width;
if (!Number.isInteger(height)) {
throw new ToolError('errors.pixelCountMismatch', {
count: tokens.length,
width
});
throw new ToolError("errors.pixelCountMismatch", {
count: tokens.length,
width,
});
}
const data = new Uint8ClampedArray(tokens.length * 4);
tokens.forEach((token, index) => {
@@ -43,5 +51,5 @@ export function hexToPixels(text: string, width: number): PixelImage {
}
function byteHex(value: number): string {
return value.toString(16).padStart(2, '0');
return value.toString(16).padStart(2, "0");
}
+49 -31
View File
@@ -1,49 +1,67 @@
import { describe, expect, it } from 'vitest';
import { anchorOrigin, tileGrid, wrapText } from './textdraw';
import { describe, expect, it } from "vitest";
import { anchorOrigin, tileGrid, wrapText } from "./textdraw";
const measure = (s: string) => s.length * 10;
describe('anchorOrigin', () => {
it('углы и отступ считаются от краёв', () => {
expect(anchorOrigin('top-left', 100, 50, 400, 300, 30)).toEqual({ x: 30, y: 30 });
expect(anchorOrigin('top-right', 100, 50, 400, 300, 30)).toEqual({ x: 270, y: 30 });
expect(anchorOrigin('bottom-left', 100, 50, 400, 300, 30)).toEqual({ x: 30, y: 220 });
expect(anchorOrigin('bottom-right', 100, 50, 400, 300, 30)).toEqual({ x: 270, y: 220 });
describe("anchorOrigin", () => {
it("углы и отступ считаются от краёв", () => {
expect(anchorOrigin("top-left", 100, 50, 400, 300, 30)).toEqual({
x: 30,
y: 30,
});
expect(anchorOrigin("top-right", 100, 50, 400, 300, 30)).toEqual({
x: 270,
y: 30,
});
expect(anchorOrigin("bottom-left", 100, 50, 400, 300, 30)).toEqual({
x: 30,
y: 220,
});
expect(anchorOrigin("bottom-right", 100, 50, 400, 300, 30)).toEqual({
x: 270,
y: 220,
});
});
it('центрирование — ровно половина остатка', () => {
expect(anchorOrigin('center', 100, 50, 401, 301, 0)).toEqual({ x: 150.5, y: 125.5 });
expect(anchorOrigin('middle-left', 100, 50, 400, 300, 12)).toEqual({ x: 12, y: 125 });
expect(anchorOrigin('top-center', 100, 50, 400, 300, 8)).toEqual({ x: 150, y: 8 });
it("центрирование — ровно половина остатка", () => {
expect(anchorOrigin("center", 100, 50, 401, 301, 0)).toEqual({
x: 150.5,
y: 125.5,
});
expect(anchorOrigin("middle-left", 100, 50, 400, 300, 12)).toEqual({
x: 12,
y: 125,
});
expect(anchorOrigin("top-center", 100, 50, 400, 300, 8)).toEqual({
x: 150,
y: 8,
});
});
});
describe('wrapText', () => {
it('жадно набирает строки в пределах ширины', () => {
describe("wrapText", () => {
it("жадно набирает строки в пределах ширины", () => {
// measure: 10px за символ → строка ≤ 120px = 12 символов
expect(wrapText('один два три четыре пять', 120, measure)).toEqual([
'один два три',
'четыре пять'
expect(wrapText("один два три четыре пять", 120, measure)).toEqual([
"один два три",
"четыре пять",
]);
});
it('слово длиннее ширины уходит на отдельную строку целиком', () => {
expect(wrapText('короткое сверхдлинноеслово без переносов', 90, measure)).toEqual([
'короткое',
'сверхдлинноеслово',
'без',
'переносов'
]);
it("слово длиннее ширины уходит на отдельную строку целиком", () => {
expect(
wrapText("короткое сверхдлинноеслово без переносов", 90, measure),
).toEqual(["короткое", "сверхдлинноеслово", "без", "переносов"]);
});
it('пустой и пробельный текст дают пустой массив', () => {
expect(wrapText('', 100, measure)).toEqual([]);
expect(wrapText(' \n\t ', 100, measure)).toEqual([]);
it("пустой и пробельный текст дают пустой массив", () => {
expect(wrapText("", 100, measure)).toEqual([]);
expect(wrapText(" \n\t ", 100, measure)).toEqual([]);
});
});
describe('tileGrid', () => {
it('стабильная сетка с шагом и центрированием', () => {
describe("tileGrid", () => {
it("стабильная сетка с шагом и центрированием", () => {
const pts = tileGrid(200, 200, 0, 60, 60, 80, 24);
expect(pts.length).toBeGreaterThan(0);
const xs = new Set(pts.map((p) => p.x));
@@ -52,13 +70,13 @@ describe('tileGrid', () => {
expect(ys.size).toBeGreaterThan(1);
});
it('кап защищает от гигантского количества плиток', () => {
it("кап защищает от гигантского количества плиток", () => {
const pts = tileGrid(4000, 4000, 45, 8, 8, 100, 40);
expect(pts.length).toBeLessThanOrEqual(2500);
expect(pts.length).toBeGreaterThan(0);
});
it('обычные входные данные не триггерят кап', () => {
it("обычные входные данные не триггерят кап", () => {
const pts = tileGrid(800, 600, 30, 140, 90, 160, 40);
expect(pts.length).toBeLessThanOrEqual(2500);
expect(pts.length).toBeGreaterThan(4);
+40 -23
View File
@@ -1,13 +1,13 @@
export type Position9 =
| 'top-left'
| 'top-center'
| 'top-right'
| 'middle-left'
| 'center'
| 'middle-right'
| 'bottom-left'
| 'bottom-center'
| 'bottom-right';
| "top-left"
| "top-center"
| "top-right"
| "middle-left"
| "center"
| "middle-right"
| "bottom-left"
| "bottom-center"
| "bottom-right";
/**
* Левый верхний угол контента размером contentW×contentH при размещении
@@ -19,16 +19,30 @@ export function anchorOrigin(
contentH: number,
cw: number,
ch: number,
margin: number
margin: number,
): { x: number; y: number } {
const h = position.endsWith('-left') ? 'left' : position.endsWith('-right') ? 'right' : 'center';
const v = position.startsWith('top-')
? 'top'
: position.startsWith('bottom-')
? 'bottom'
: 'middle';
const x = h === 'left' ? margin : h === 'right' ? cw - margin - contentW : (cw - contentW) / 2;
const y = v === 'top' ? margin : v === 'bottom' ? ch - margin - contentH : (ch - contentH) / 2;
const h = position.endsWith("-left")
? "left"
: position.endsWith("-right")
? "right"
: "center";
const v = position.startsWith("top-")
? "top"
: position.startsWith("bottom-")
? "bottom"
: "middle";
const x =
h === "left"
? margin
: h === "right"
? cw - margin - contentW
: (cw - contentW) / 2;
const y =
v === "top"
? margin
: v === "bottom"
? ch - margin - contentH
: (ch - contentH) / 2;
return { x, y };
}
@@ -39,12 +53,15 @@ export function anchorOrigin(
export function wrapText(
text: string,
maxWidth: number,
measure: (line: string) => number
measure: (line: string) => number,
): string[] {
const words = text.trim().split(/\s+/).filter((w) => w.length > 0);
const words = text
.trim()
.split(/\s+/)
.filter((w) => w.length > 0);
if (words.length === 0) return [];
const lines: string[] = [];
let current = '';
let current = "";
for (const word of words) {
const candidate = current.length === 0 ? word : `${current} ${word}`;
if (measure(candidate) <= maxWidth || current.length === 0) {
@@ -75,7 +92,7 @@ export function tileGrid(
stepX: number,
stepY: number,
blockW: number,
blockH: number
blockH: number,
): TilePoint[] {
const diag = Math.sqrt(cw * cw + ch * ch);
const spanX = diag + blockW;
@@ -101,7 +118,7 @@ export function tileGrid(
for (let c = 0; c < cols; c++) {
points.push({
x: startX + c * sx - cw / 2,
y: startY + r * sy - ch / 2
y: startY + r * sy - ch / 2,
});
}
}
+26 -24
View File
@@ -1,4 +1,4 @@
import { describe, expect, it } from 'vitest';
import { describe, expect, it } from "vitest";
import {
base64ToBytes,
bytesToImage,
@@ -6,58 +6,60 @@ import {
imageToRgbValues,
looksLikePng,
rgbValuesToImage,
stripDataUri
} from './textio';
import { makeImage } from './test-helpers';
stripDataUri,
} from "./textio";
import { makeImage } from "./test-helpers";
const img = makeImage(2, 1, [
[255, 0, 0, 255],
[0, 255, 0, 128]
[0, 255, 0, 128],
]);
describe('bytes', () => {
it('round-trip rows → image → rows', () => {
describe("bytes", () => {
it("round-trip rows → image → rows", () => {
const rows = imageToByteRows(img);
expect(rows).toBe('255 0 0 255 0 255 0 128');
expect(rows).toBe("255 0 0 255 0 255 0 128");
const back = bytesToImage(rows, 2);
expect([...back.data]).toEqual([...img.data]);
});
it('некратное четырём число байт — ошибка', () => {
expect(() => bytesToImage('1 2 3', 1)).toThrow(/errors\.bytesCount/);
it("некратное четырём число байт — ошибка", () => {
expect(() => bytesToImage("1 2 3", 1)).toThrow(/errors\.bytesCount/);
});
it('значение вне 0..255 — ошибка диапазона', () => {
expect(() => bytesToImage('10 20 30 256', 1)).toThrow(/errors\.byteRange/);
it("значение вне 0..255 — ошибка диапазона", () => {
expect(() => bytesToImage("10 20 30 256", 1)).toThrow(/errors\.byteRange/);
});
});
describe('rgb values', () => {
it('round-trip rgba-строк', () => {
describe("rgb values", () => {
it("round-trip rgba-строк", () => {
const rows = imageToRgbValues(img);
expect(rows.split('\n')[0]).toBe('rgba(255, 0, 0, 255) rgba(0, 255, 0, 128)');
const back = rgbValuesToImage(rows.replace(/rgba\(|\)/g, ''), 2);
expect(rows.split("\n")[0]).toBe(
"rgba(255, 0, 0, 255) rgba(0, 255, 0, 128)",
);
const back = rgbValuesToImage(rows.replace(/rgba\(|\)/g, ""), 2);
expect([...back.data]).toEqual([...img.data]);
});
});
describe('png signature / data-uri', () => {
it('looksLikePng: настоящая сигнатура и обрывок', () => {
describe("png signature / data-uri", () => {
it("looksLikePng: настоящая сигнатура и обрывок", () => {
const good = new Uint8Array([137, 80, 78, 71, 13, 10, 26, 10, 1]);
const bad = new Uint8Array([137, 80, 78]);
expect(looksLikePng(good)).toBe(true);
expect(looksLikePng(bad)).toBe(false);
});
it('stripDataUri снимает префикс и оставляет чистый base64', () => {
expect(stripDataUri('data:image/png;base64,iVBORw==')).toBe('iVBORw==');
expect(stripDataUri(' iVBORw==')).toBe('iVBORw==');
it("stripDataUri снимает префикс и оставляет чистый base64", () => {
expect(stripDataUri("data:image/png;base64,iVBORw==")).toBe("iVBORw==");
expect(stripDataUri(" iVBORw==")).toBe("iVBORw==");
});
});
describe('base64ToBytes', () => {
it('декодирует известную строку', () => {
const bytes = base64ToBytes('AAECAwQ=');
describe("base64ToBytes", () => {
it("декодирует известную строку", () => {
const bytes = base64ToBytes("AAECAwQ=");
expect([...bytes]).toEqual([0, 1, 2, 3, 4]);
});
});
+29 -19
View File
@@ -1,6 +1,6 @@
import { ToolError } from './errors';
import type { PixelImage } from './types';
import { createPixelImage } from './types';
import { ToolError } from "./errors";
import type { PixelImage } from "./types";
import { createPixelImage } from "./types";
const PNG_SIGNATURE = [0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a];
@@ -11,25 +11,30 @@ export function imageToByteRows(img: PixelImage): string {
const parts: string[] = [];
for (let x = 0; x < img.width; x++) {
const i = (y * img.width + x) * 4;
parts.push(`${img.data[i]} ${img.data[i + 1]} ${img.data[i + 2]} ${img.data[i + 3]}`);
parts.push(
`${img.data[i]} ${img.data[i + 1]} ${img.data[i + 2]} ${img.data[i + 3]}`,
);
}
rows.push(parts.join(' '));
rows.push(parts.join(" "));
}
return rows.join('\n');
return rows.join("\n");
}
export function bytesToImage(text: string, width: number): PixelImage {
const nums = (text.match(/-?\d+/g) ?? []).map(Number);
if (nums.length % 4 !== 0) {
throw new ToolError('errors.bytesCount', { count: nums.length });
throw new ToolError("errors.bytesCount", { count: nums.length });
}
if (nums.some((n) => !Number.isInteger(n) || n < 0 || n > 255)) {
throw new ToolError('errors.byteRange');
throw new ToolError("errors.byteRange");
}
const w = Math.trunc(width);
if (!Number.isInteger(w) || w < 1) throw new ToolError('errors.widthInt');
if (nums.length / 4 % w !== 0) {
throw new ToolError('errors.pixelCountMismatch', { count: nums.length / 4, width: w });
if (!Number.isInteger(w) || w < 1) throw new ToolError("errors.widthInt");
if ((nums.length / 4) % w !== 0) {
throw new ToolError("errors.pixelCountMismatch", {
count: nums.length / 4,
width: w,
});
}
const out = createPixelImage(w, nums.length / 4 / w);
out.data.set(nums);
@@ -43,26 +48,31 @@ export function imageToRgbValues(img: PixelImage): string {
const parts: string[] = [];
for (let x = 0; x < img.width; x++) {
const i = (y * img.width + x) * 4;
parts.push(`rgba(${img.data[i]}, ${img.data[i + 1]}, ${img.data[i + 2]}, ${img.data[i + 3]})`);
parts.push(
`rgba(${img.data[i]}, ${img.data[i + 1]}, ${img.data[i + 2]}, ${img.data[i + 3]})`,
);
}
rows.push(parts.join(' '));
rows.push(parts.join(" "));
}
return rows.join('\n');
return rows.join("\n");
}
export function rgbValuesToImage(text: string, width: number): PixelImage {
const nums = (text.match(/-?\d+(?:\.\d+)?/g) ?? []).map(Number);
if (nums.length % 4 !== 0) {
throw new ToolError('errors.bytesCount', { count: nums.length });
throw new ToolError("errors.bytesCount", { count: nums.length });
}
if (nums.some((n) => !Number.isInteger(n) || n < 0 || n > 255)) {
throw new ToolError('errors.byteRange');
throw new ToolError("errors.byteRange");
}
const w = Math.trunc(width);
if (!Number.isInteger(w) || w < 1) throw new ToolError('errors.widthInt');
if (!Number.isInteger(w) || w < 1) throw new ToolError("errors.widthInt");
const pxCount = nums.length / 4;
if (pxCount % w !== 0) {
throw new ToolError('errors.pixelCountMismatch', { count: pxCount, width: w });
throw new ToolError("errors.pixelCountMismatch", {
count: pxCount,
width: w,
});
}
const out = createPixelImage(w, pxCount / w);
out.data.set(nums);
@@ -76,7 +86,7 @@ export function stripDataUri(text: string): string {
}
export function base64ToBytes(text: string): Uint8Array {
const clean = text.replace(/\s+/g, '');
const clean = text.replace(/\s+/g, "");
const binary = atob(clean);
const bytes = new Uint8Array(binary.length);
for (let i = 0; i < binary.length; i++) bytes[i] = binary.charCodeAt(i);
+1 -1
View File
@@ -8,7 +8,7 @@ export function createPixelImage(width: number, height: number): PixelImage {
return {
width,
height,
data: new Uint8ClampedArray(width * height * 4)
data: new Uint8ClampedArray(width * height * 4),
};
}