Skip to content

Instantly share code, notes, and snippets.

@tomhermans
Last active April 19, 2025 14:33
Show Gist options
  • Save tomhermans/29f0ed91a46124d5c0a81ec515d50e10 to your computer and use it in GitHub Desktop.
Save tomhermans/29f0ed91a46124d5c0a81ec515d50e10 to your computer and use it in GitHub Desktop.
/* Image Resize and Compress Script
* --------------------------------
* This script resizes images in a specified folder and saves them to a new folder with a timestamp. It allows the user to specify the target width, height, and compression quality. The script also handles errors gracefully and provides feedback on the processing status.
*
* Features:
* - Interactive prompts for input folder, dimensions, and compression
* - Preserves aspect ratio (optional)
* - Creates a timestamped output folder
* - Applies JPEG compression with quality control
* - Handles JPG, JPEG, and PNG files
*
* Usage:
* node resize-free.js
*
* Dependencies:
* - sharp (for image processing)
* - fs, path (Node.js core modules)
*
* /
/*
Prerequisites
Make sure you have Node.js installed (v16 or higher recommended)
Make sure the sharp package is installed:
npm install sharp
Running the Script: node resize-images.js
Save the script as resize-free.js in your project folder
Open your terminal or command prompt
Navigate to the folder containing the script
Run the script: node resize-free.js
*/
const fs = require('fs');
const path = require('path');
const sharp = require('sharp');
// Get input folder from command line argument or use default
const inputFolder = process.argv[2] || './input';
const outputFolder = './output';
console.log(`Input folder: ${inputFolder}`);
console.log(`Output folder: ${outputFolder}`);
// Create output folder if it doesn't exist
if (!fs.existsSync(outputFolder)) {
fs.mkdirSync(outputFolder);
console.log(`Created output folder: ${outputFolder}`);
}
// Check if input folder exists
if (!fs.existsSync(inputFolder)) {
console.error(`Error: Input folder '${inputFolder}' does not exist.`);
process.exit(1);
}
// Process each file in the input folder
fs.readdir(inputFolder, (err, files) => {
if (err) {
console.error('Error reading input folder:', err);
return;
}
console.log(`Found ${files.length} files in input folder.`);
let processedCount = 0;
let errorCount = 0;
files.forEach(file => {
if (file.match(/\.(jpg|jpeg|png)$/i)) {
const inputPath = path.join(inputFolder, file);
const outputFileName = `${path.parse(file).name}-1024.jpg`;
const outputPath = path.join(outputFolder, outputFileName);
console.log(`Processing: ${file}`);
sharp(inputPath)
.resize({
width: 1024,
height: 1024,
fit: sharp.fit.contain,
background: { r: 255, g: 255, b: 255, alpha: 1 }
})
.toFormat('jpeg')
.toFile(outputPath)
.then(() => {
console.log(`Successfully processed: ${file} -> ${outputFileName}`);
processedCount++;
if (processedCount + errorCount === files.length) {
console.log(`\nProcessing complete. ${processedCount} files processed, ${errorCount} errors.`);
}
})
.catch(err => {
console.error(`Error processing ${file}:`, err);
errorCount++;
if (processedCount + errorCount === files.length) {
console.log(`\nProcessing complete. ${processedCount} files processed, ${errorCount} errors.`);
}
});
} else {
console.log(`Skipping non-image file: ${file}`);
}
});
if (files.length === 0) {
console.log('No files found to process.');
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment