Optimize images from a Node.js script
By Flavio Copes
Learn how to optimize images from a Node.js script with sharp, converting a PNG to lossless webp and resizing or rotating it in just a few lines.
One tool I’ve been using to optimize images is sharp.
import sharp from 'sharp'
Here’s how I used it to convert images to webp:
await sharp('image.png')
.webp({ lossless: true })
.toFile('image.webp')
For photographs, lossy WebP is usually much smaller than lossless WebP. You can resize the image, correct its orientation from EXIF metadata, and set a quality in the same pipeline:
await sharp('photo.jpg')
.rotate()
.resize({ width: 1600, withoutEnlargement: true })
.webp({ quality: 82 })
.toFile('photo.webp')
withoutEnlargement prevents a small source image from being scaled up. Keep the original until you have visually checked the output, especially when changing formats or using lossy compression.
If you just need to resize or compress a couple of images without writing a script, I made a browser-based image resizer tool — nothing gets uploaded anywhere.
Related posts about node: