How to Convert an Image to WebP Format using Node.js
If you’re trying to retain the quality of an image file while still achieving sizeable compression, WebP is one of the best image formats out there to use. Thankfully, there’s an API for that: our WebP Conversion API will allow you to quickly convert dozens of common file formats to WebP in the blink of an eye. The below demonstration is intended to help you structure an API call using ready-to-run code snippets in Node.js, beginning with SDK installation & ending with API key authentication.
To install the Node.js SDK, run the following command:
npm install cloudmersive-image-api-client --save
Once that’s done, copy in the remaining code to call the image conversion function, and include your API key in the authorization snippet (you can get a key by registering a free account on our website):
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);
Now you’re all set — pretty easy, right? You can take advantage of dozens of other Cloudmersive APIs for free using similar code snippets & SDK installation instructions on the Cloudmersive API Console.