Created
October 2, 2021 16:00
-
-
Save tennox/f949bf91eb1b8f206cf3f4d3a9b23734 to your computer and use it in GitHub Desktop.
Gulp task to downscale & convert images using sharp
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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/')) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
fancy. thanks!