The digital age has brought images to the forefront of our browsing experience. However, the catch is that these images can often take up considerable bandwidth, affecting website performance. We can combat this by reducing image size through a process called Image Optimization. In this article, we will explore how to convert image files such as PNG and JPG to WebP and compress them using Node.js.
WebP, a modern image format developed by Google, provides superior lossless and lossy compression for web images. By converting PNG and JPG files to WebP, we can achieve smaller file sizes without compromising image quality, ultimately making our websites load faster.
Before we start the conversion process, let's make sure we have Node.js installed. If not, download and install it according to your operating system.
We will use two npm packages: sharp
for image conversion, and imagemin-webp
for image compression.
npm install sharp imagemin imagemin-webp
Let's use the sharp
module to convert a PNG or JPG image to WebP. This is done by reading the input file and transforming it into the WebP format.
const sharp = require('sharp');
sharp('input.png')
.webp()
.toFile('output.webp')
.then(() => console.log('Image conversion complete.'))
.catch(err => console.error(err));
Next, let's compress the converted WebP image using the imagemin-webp
module.
const imagemin = require('imagemin');
const imageminWebp = require('imagemin-webp');
(async () => {
await imagemin(['output.webp'], {
destination: 'compressed_images',
plugins: [
imageminWebp({quality: 50})
]
});
console.log('Image compression complete.');
})();
const sharp = require('sharp');
const imagemin = require('imagemin');
const imageminWebp = require('imagemin-webp');
sharp('input.png')
.webp()
.toFile('output.webp')
.then(() => {
(async () => {
await imagemin(['output.webp'], {
destination: 'compressed_images',
plugins: [
imageminWebp({quality: 50})
]
});
console.log('Image conversion and compression complete.');
})();
})
.catch(err => console.error(err));
This full script will convert your image to WebP format and compress it.
There you have it: an efficient way to convert and compress PNG, JPG to WebP in Node.js. Now you can optimize your images, speed up your website load times, and provide a better user experience. With a bit of practice, these steps will become second nature.
imagemin-webp
plugin allows you to adjust the quality parameter to control the compression level.CloneCoding
Innovation Starts with a Single Line of Code!