Skip to content

Instantly share code, notes, and snippets.

@wtype
Created March 27, 2025 16:12
Show Gist options
  • Select an option

  • Save wtype/a0bc1eaed886c60e50bbfd203517e39e to your computer and use it in GitHub Desktop.

Select an option

Save wtype/a0bc1eaed886c60e50bbfd203517e39e to your computer and use it in GitHub Desktop.
import fs from 'fs';
import path from 'path';
import sharp from 'sharp';
function addPngExtension(path: string) {
return path.split(".").at(0) + ".png";
}
function ensureDir(dirPath: string): Promise<void> {
return new Promise((resolve, reject) => {
const fullPath = path.resolve(dirPath);
fs.stat(fullPath, (err, stats) => {
if (err && err.code === 'ENOENT') {
fs.mkdir(fullPath, { recursive: true }, (mkdirErr) => {
if (mkdirErr) {
reject(mkdirErr);
} else {
resolve();
}
});
} else if (stats && stats.isDirectory()) {
resolve();
} else {
reject(new Error(`${fullPath} is not a directory`));
}
});
});
}
async function processImages(inputFolder = "input", outputFolder = "output", size = 175) {
try {
await Promise.all([ensureDir(inputFolder), ensureDir(outputFolder)])
const files = await fs.promises.readdir(inputFolder);
const imageFiles = files.filter(file => {
const ext = path.extname(file).toLowerCase();
return ['.jpg', '.jpeg', '.png', '.heic'].includes(ext);
});
for (const file of imageFiles) {
const inputPath = path.join(inputFolder, file);
const outputPath = path.join(outputFolder, file);
sharp(inputPath)
.grayscale()
.resize(size, size, { fit: "cover" })
.toFormat("png")
.toFile(addPngExtension(outputPath), (err, info) => {
if (err) {
console.error(`Error processing ${file}:`, err);
} else {
console.log(`Processed ${file}:`, info);
}
});
}
} catch (error) {
console.error('Error:', error);
}
}
await processImages();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment