diff --git a/src/scripts/remove-bg.mjs b/src/scripts/remove-bg.mjs index a9ea578..3b8b615 100644 --- a/src/scripts/remove-bg.mjs +++ b/src/scripts/remove-bg.mjs @@ -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; }) );