Skip to content

Instantly share code, notes, and snippets.

@tennox
Created October 2, 2021 16:00
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tennox/f949bf91eb1b8f206cf3f4d3a9b23734 to your computer and use it in GitHub Desktop.
Save tennox/f949bf91eb1b8f206cf3f4d3a9b23734 to your computer and use it in GitHub Desktop.
Gulp task to downscale & convert images using sharp
const gulp = require('gulp')
const rename = require('gulp-rename')
const sharp = require('sharp')
var useAsync = require('gulp-use').async
export default function convertImages () {
return gulp
.src('static/original/uploads/*.*')
.pipe(useAsync(async function (file, next) {
try {
const input = sharp(file.contents)
console.log(file.relative)
const newImage = input
.rotate() // physically rotate according to metadata (as browser often ignore orientation meta for webp) - https://stackoverflow.com/a/58828508
.resize({
width: 1024,
height: 786,
fit: 'inside', // interprets the above as maximum bounds
withoutEnlargement: true, // don't enlarge if within bounds
})
.toFormat('webp')
// const newImageWithOrientation = await sharp(await newImage.toBuffer())
// .withMetadata({ orientation: meta.orientation })
// console.log('-> newMeta:', (await newImageWithOrientation.metadata()).orientation)
file.contents = await newImage.toBuffer()
next(null, file)
} catch (err) {
console.error(file, err)
return next(err)
}
})
)
.pipe(rename({ extname: '.webp' }))
.pipe(gulp.dest('static/uploads/'))
}
@gotjoshua
Copy link

fancy. thanks!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment