Skip to content

Instantly share code, notes, and snippets.

@solarsailer
Last active May 23, 2020 22:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save solarsailer/91953c0b180b2965d223ed5a7ecbd86a to your computer and use it in GitHub Desktop.
Save solarsailer/91953c0b180b2965d223ed5a7ecbd86a to your computer and use it in GitHub Desktop.
Create variants for an image (based on https://github.com/tmcw/bespoke)
#!/usr/bin/env node
const fs = require('fs')
const sharp = require('sharp')
const prettyBytes = require('pretty-bytes')
// -------------------------------------------------------------
// Script.
//
// Note: for optimal file sizes, export at highest quality
// and resolution in Lightroom.
//
// I don't know why, but from all the tests I made, this is what
// gives the smallest file sizes for the images generated here.
// -------------------------------------------------------------
if (process.argv.length !== 3) {
console.error('usage: pl-convert file.jpg')
process.exit(0)
}
const RESOLUTIONS = [500, 1000, 1500, 2400]
const name = process.argv[2] // Get arg.
const shortname = name.replace(/\.[^/.]+$/, '') // Remove extension.
const image = fs.readFileSync(name) // Read file buffer.
// Export an image in 4 sizes and in 2 formats.
// Remove the metadata.
// Do not enlarge.
// Use largest edge for resize (if portrait, height, if landscape, width).
!(async () => {
const {width, height} = await sharp(image).metadata()
for (let res of RESOLUTIONS) {
const jpg = `${shortname}_${res}.jpg`
const webp = `${shortname}_${res}.webp`
const options = {withoutEnlargement: true}
if (width >= height) options.width = res
else options.height = res
await sharp(image).resize(options).jpeg({quality: 75}).toFile(jpg)
await sharp(image).resize(options).webp({quality: 75}).toFile(webp)
log(jpg)
log(webp)
}
})()
function log(filename) {
const size = prettyBytes(fs.readFileSync(filename).byteLength)
console.log(`${filename}: ${size}`)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment