mirror of
https://github.com/Ku6epXBOCTuK/easy-png-tools.git
synced 2026-09-14 21:46:35 +00:00
feat: add show mask workflow
This commit is contained in:
@@ -1,5 +1,5 @@
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { flattenOntoColor, parseHex, removeColorToAlpha } from './alpha';
|
||||
import { colorMask, flattenOntoColor, parseHex, removeColorToAlpha } from './alpha';
|
||||
import { makeImage } from './test-helpers';
|
||||
|
||||
describe('removeColorToAlpha', () => {
|
||||
@@ -55,6 +55,34 @@ describe('removeColorToAlpha', () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe('colorMask', () => {
|
||||
it('удаляемые пиксели белые, остальные чёрные, маска непрозрачная', () => {
|
||||
const out = colorMask(
|
||||
makeImage(2, 1, [
|
||||
[255, 0, 0, 255],
|
||||
[0, 255, 0, 255]
|
||||
]),
|
||||
'#ff0000',
|
||||
0
|
||||
);
|
||||
expect([...out.data]).toEqual([
|
||||
255, 255, 255, 255,
|
||||
0, 0, 0, 255
|
||||
]);
|
||||
});
|
||||
|
||||
it('порог совпадает с removeColorToAlpha', () => {
|
||||
const img = makeImage(2, 1, [
|
||||
[0, 0, 0, 255],
|
||||
[128, 128, 128, 255]
|
||||
]);
|
||||
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');
|
||||
|
||||
@@ -22,6 +22,24 @@ export function removeColorToAlpha(
|
||||
return out;
|
||||
}
|
||||
|
||||
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 thresholdSq = tolerance * tolerance;
|
||||
const out = createPixelImage(img.width, img.height);
|
||||
for (let i = 0; i < out.data.length; i += 4) {
|
||||
const dr = img.data[i] - targetR;
|
||||
const dg = img.data[i + 1] - targetG;
|
||||
const db = img.data[i + 2] - targetB;
|
||||
const matched = dr * dr + dg * dg + db * db <= thresholdSq;
|
||||
out.data[i] = matched ? 255 : 0;
|
||||
out.data[i + 1] = matched ? 255 : 0;
|
||||
out.data[i + 2] = matched ? 255 : 0;
|
||||
out.data[i + 3] = 255;
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
export function flattenOntoColor(img: PixelImage, hex: string): PixelImage {
|
||||
const [bgR, bgG, bgB] = parseHex(hex);
|
||||
const out = createPixelImage(img.width, img.height);
|
||||
|
||||
Reference in New Issue
Block a user