Skip to content

Instantly share code, notes, and snippets.

@tomgp
Created September 27, 2017 13:54
Show Gist options
  • Save tomgp/08680d099acb1e59d72bab6f01a8151b to your computer and use it in GitHub Desktop.
Save tomgp/08680d099acb1e59d72bab6f01a8151b to your computer and use it in GitHub Desktop.
convert a bunch of files using nodejs and the sips utility on osx
const fs = require('fs');
const path = require('path');
const { spawn } = require('child_process');
const root = './';
const sizes = {
s:300,
m:600,
l:1200,
};
const getImages = (filePath) => {
let isImage = false;
['png','gif','jpg'].forEach((ext)=>{
isImage = (path.extname(filePath).indexOf(ext) >= 0) || isImage;
});
return isImage;
}
const getDirectories = (filePath) => {
return fs.lstatSync(filePath).isDirectory()
}
const imageResize = (imagePath, outputPath, sizes) => {
Object.entries(sizes).forEach(([key, value])=>{
const outFile = path.join(outputPath, key, path.parse(imagePath).base);
const sips = spawn('sips', [imagePath, '-Z', value, '--out', outFile]);
sips.stdout.on('data', (data) => {
console.log(`converting... ${data}`);
});
sips.stderr.on('data', (data) => {
console.log(`ERROR: ${data}`);
});
sips.on('close', (code) => {
console.log(`finished ${outFile}. exit code ${code}`);
});
})
}
const sourceDirs = fs.readdirSync(root).filter(getDirectories);
sourceDirs.forEach((str) => {
const subpath = path.join(root, str);
Object.keys(sizes).forEach((key)=>{
//check / create output directories
const dirName = path.join(subpath, key)
if (!fs.existsSync( dirName )){
fs.mkdirSync( dirName );
}
});
fs.readdirSync(subpath)
.filter(getImages)
.map((imageFile) => {
return path.join(subpath, imageFile)
})
.forEach((imagePath)=>{
imageResize(imagePath, subpath, sizes);
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment