Skip to content

Instantly share code, notes, and snippets.

@qant
Created December 14, 2021 15:12
Show Gist options
  • Save qant/5abd1c56b2e400e646ad8dbfa0774eee to your computer and use it in GitHub Desktop.
Save qant/5abd1c56b2e400e646ad8dbfa0774eee to your computer and use it in GitHub Desktop.
Resize and watermark images node
{ "name": "resize_and_watermark_images", "version": "1.0.0", "description": "", "main": "resize.js", "author": "Anton Semenov", "license": "", "dependencies": { "sharp": "^0.29.3" } }
// npm install
// create /images and /resized folders
// node resize.js to run
// images must be in in /images folder
// resized and watermarked images will appear in /resized folder
// watermarkImage must be in root folder
const http = require('https');
const path = require('path');
const fs = require('fs');
const sharp = require('sharp');
const sizes = [[150,150],[570,340],[385,258],[933,622],[1270,950]];
const quality = 82;
const imageFolder = 'images';
const imageFolderResized = 'resized';
const watermarkImage = 'final_logokey.png';
const extractFileNames = function (err,files){
if (!err){
files.forEach(fileName=>{
let fullFileName = path.join(__dirname,imageFolder, fileName);
let f_name = path.parse(fileName).name;
let f_ext = path.parse(fileName).ext;
sizes.forEach(size=>{
size_f_name = f_name+'-'+size[0]+'x'+size[1]+f_ext;
console.log('Working on '+fullFileName);
//if (size[0] > 933 || size[0] === 1270){
if (size[0] >= 933){ // sizes width >= 933 will be watermarked
sharp(fullFileName,{ failOnError: false })
.resize(size[0],size[1])
.composite([{ input: watermarkImage, gravity: 'center' }])
.jpeg({
mozjpeg: true,
quality: quality,
//chromaSubsampling: '4:4:4'
})
.toFile(path.join(__dirname, imageFolderResized, size_f_name))
.then(data=>{
console.log(size_f_name+' Is saved and watermarked');
}).catch(err=>{
console.log(size_f_name+' Error:');
console.log(err)
});
}else{
console.log('Working on '+fullFileName);
sharp(fullFileName,{ failOnError: false })
.resize(size[0],size[1])
.jpeg({
mozjpeg: true,
quality: 75,
//chromaSubsampling: '1:2:2'
})
.toFile(path.join(__dirname, imageFolderResized, size_f_name))
.then(data=>{
console.log(size_f_name+' Is saved');
}).catch(err=>{
console.log(size_f_name+' Error:');
console.log(err)
});
}
});
});
//fs.readFile()
}
}
fs.readdir(imageFolder,extractFileNames);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment