Skip to content

Instantly share code, notes, and snippets.

@tancredi
Created July 15, 2022 12:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tancredi/cc55e4200ed1c0763163a329c4e6d37d to your computer and use it in GitHub Desktop.
Save tancredi/cc55e4200ed1c0763163a329c4e6d37d to your computer and use it in GitHub Desktop.
Image resize script
#!/usr/bin/env node
const color = require('cli-color');
const Jimp = require('jimp');
const [inputFile, resizeInput, outputFile] = process.argv.slice(2);
const usage = () => {
console.log(
color.red(
`Usage: resize [input-file] [[width]x[height]|[percent]%] <output-file>`
)
);
process.exit(1);
};
const isNumeric = value => String(Number(value)) === String(value);
const scaleByPercentage = (image, input) => {
const amount = Number(input.slice(0, -1)) / 100;
if (!isNumeric(amount)) {
throw new Error(`Invalid scale amount: ${amount}`);
}
return image.scale(amount);
};
const resizeWithBothSides = (image, input) => {
const sizes = input.split('x');
const [sizeX, sizeY] = sizes;
if (sizes.length !== 2 || !isNumeric(sizeX) || !isNumeric(sizeY)) {
throw new Error('Invalid resize amounts');
}
return image.resize(Number(sizeX), Number(sizeY));
};
const run = async () => {
if (!inputFile || !resizeInput) {
return usage();
}
const image = await Jimp.read(inputFile);
if (resizeInput.endsWith('%')) {
// e.g. `50%`
scaleByPercentage(image, resizeInput);
} else if (resizeInput.includes('x')) {
// e.g. `200x150`
resizeWithBothSides(image, resizeInput);
} else {
throw new Error('Invalid resize amounts');
}
image.quality(100);
await image.writeAsync(outputFile || inputFile);
console.log(`${color.green('✓')} Saved resized to ${outputFile}`);
};
return run();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment