Last active
April 21, 2023 14:51
-
-
Save fedetibaldo/55dac42a99c9fa8dceaa8204accff300 to your computer and use it in GitHub Desktop.
Requires the imagemagick CLI tool.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { readdir } from 'fs/promises'; | |
import path from 'path'; | |
import im from 'imagemagick'; | |
import { promisify } from 'util'; | |
const PHOTOS_PATH = path.join(process.cwd(), '/public/assets/photos/'); | |
const MAX_WIDTH = 1920; | |
const identifyWidth = promisify( | |
(filePath: string, callback: (err: any, result: string) => void) => { | |
return im.identify(['-format', '%w', filePath], callback); | |
} | |
); | |
const resize = promisify(im.resize); | |
(async () => { | |
const fileNames = await readdir(PHOTOS_PATH); | |
for (const fileName of fileNames) { | |
const srcPath = path.join(PHOTOS_PATH, fileName); | |
console.log(`[${fileName}] 🔎 Identifying...`); | |
const width = parseInt(await identifyWidth(srcPath)); | |
if (typeof width == 'number' && width > MAX_WIDTH) { | |
console.log(`[${fileName}] ◲ Resizing...`); | |
await resize({ | |
srcPath, | |
dstPath: srcPath, | |
width: MAX_WIDTH, | |
customArgs: ['-auto-orient'], | |
}); | |
console.log(`[${fileName}] ✅ Resized!`); | |
} else { | |
console.log(`[${fileName}] ➡️ Skipping.`); | |
} | |
} | |
})(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment