Skip to content

Instantly share code, notes, and snippets.

@cbfn
Created December 5, 2018 18:48
Show Gist options
  • Save cbfn/ac3e63cba4850429d4a73868d1a540b1 to your computer and use it in GitHub Desktop.
Save cbfn/ac3e63cba4850429d4a73868d1a540b1 to your computer and use it in GitHub Desktop.
Image resize using node.js
const im = require('imagemagick');
const fs = require('fs');
const mime = require('mime-types');
fs.readdir('./uploads/', (err, filenames) => {
if (err) throw err;
filenames.forEach((filename) => {
if (mime.lookup(filename) && mime.lookup(filename).includes('image')) {
fs.readFile('./uploads/' + filename, (err, data) => {
if (!filename) {
console.log('There was an error with the image');
} else {
const path = `./uploads/${filename}`;
const thumbPath = `./uploads/thumb-${filename}`;
fs.writeFile(path, data, err => {
im.resize(
{
srcPath: path,
dstPath: thumbPath,
quality: 0.70,
height: 250
},
(err, stdout, stderr) => {
if (err) throw err;
console.log('resized image to fit within 250px');
}
);
});
}
});
}
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment