How to Convert Images to WebP Format in Node.js
2 min readNov 22, 2023
In some cases, we can achieve faster web page loading speeds when we convert our images to WebP format.
Using the below code, we can easily take advantage of a free API to convert our images to WebP. We can use this service in our Node.js applications, and we can make up to 800 API calls per month with a free-tier API key.
To get started, let’s install the SDK. We can either run the following command:
npm install cloudmersive-image-api-client --save
Or we can add this snippet to our package.json:
"dependencies": {
"cloudmersive-image-api-client": "^1.3.4"
}
Lastly, we can use the below code to call the function:
var CloudmersiveImageApiClient = require('cloudmersive-image-api-client');
var defaultClient = CloudmersiveImageApiClient.ApiClient.instance;
// Configure API key authorization: Apikey
var Apikey = defaultClient.authentications['Apikey'];
Apikey.apiKey = 'YOUR API KEY';
var apiInstance = new CloudmersiveImageApiClient.ConvertApi();
var imageFile = Buffer.from(fs.readFileSync("C:\\temp\\inputfile").buffer); // File | Image file to perform the operation on. Common file formats such as PNG, JPEG are supported.
var callback = function(error, data, response) {
if (error) {
console.error(error);
} else {
console.log('API called successfully. Returned data: ' + data);
}
};
apiInstance.convertToWebP(imageFile, callback);
And just like that, we’re all set — no more code required!