feat: update remove-bg

This commit is contained in:
Oleg Proskurin 2026-03-01 21:36:42 +07:00
parent eb7f1ed0c7
commit 2bdee2076e
1 changed files with 16 additions and 8 deletions

View File

@ -7,7 +7,7 @@ const PROJECT_ROOT = resolve(fileURLToPath(import.meta.url), '../../..');
const DEFAULT_INPUT = resolve(PROJECT_ROOT, 'assets/icons/pack2');
const DEFAULT_THRESHOLD = 230;
const DEFAULT_FUZZ = 0;
const PNG_EXTENSION = /\.png$/i;
const IMAGE_EXTENSION = /\.(png|jpe?g|webp)$/i;
function parseArgs(args) {
const result = { input: DEFAULT_INPUT, threshold: DEFAULT_THRESHOLD, fuzz: DEFAULT_FUZZ };
@ -22,7 +22,7 @@ function parseArgs(args) {
function collectFiles(input) {
if (statSync(input).isFile()) return [input];
return readdirSync(input)
.filter(f => PNG_EXTENSION.test(f))
.filter(f => IMAGE_EXTENSION.test(f))
.sort()
.map(f => join(input, f));
}
@ -135,6 +135,12 @@ function applyAntiAlias(data, width, height, transparent, fuzz) {
}
}
function outputPath(filePath) {
const ext = extname(filePath).toLowerCase();
if (ext === '.png') return filePath;
return join(resolve(filePath, '..'), basename(filePath, extname(filePath)) + '.png');
}
async function removeBackground(filePath, threshold, fuzz) {
const { data, info } = await sharp(filePath)
.ensureAlpha()
@ -145,11 +151,12 @@ async function removeBackground(filePath, threshold, fuzz) {
const { transparent, count } = floodFillFromEdges(data, width, height, threshold);
applyAntiAlias(data, width, height, transparent, fuzz);
const outFile = outputPath(filePath);
await sharp(data, { raw: { width, height, channels: 4 } })
.png()
.toFile(filePath);
.toFile(outFile);
return count;
return { count, outFile };
}
async function main() {
@ -163,7 +170,7 @@ async function main() {
const files = collectFiles(input);
if (files.length === 0) {
console.error(`No PNG files found in: ${input}`);
console.error(`No image files found in: ${input}`);
process.exit(1);
}
@ -171,9 +178,10 @@ async function main() {
const results = await Promise.all(
files.map(async (filePath) => {
const removed = await removeBackground(filePath, threshold, fuzz);
console.log(` ${basename(filePath)} -> ${removed} pixels made transparent`);
return removed;
const { count, outFile } = await removeBackground(filePath, threshold, fuzz);
const suffix = outFile !== filePath ? ` (saved as ${basename(outFile)})` : '';
console.log(` ${basename(filePath)} -> ${count} pixels made transparent${suffix}`);
return count;
})
);