How to Convert an Image to JPG/JPEG Format using Node.js
JPEG’s are one of the most common image file types out there. With our JPEG Conversion API, you can easily convert dozens of common image formats to JPEGs in the blink of an eye, and include that operation as a cloud service in your app. Given the quality loss that can occur with JPEG conversions, this API also includes a Quality parameter which allows you to specify the degree of compression for your converted file (values range from 1–100). In the below demonstration, we’ll walk through how you can use this API by structuring your API call with ready-to-run Node.js code snippets.
First things first — run this command to install the Node.js SDK:
npm install cloudmersive-image-api-client --save
Next, include the API client and API key authenticator snippets. To get a Cloudmersive API key, just register 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';
Lastly, call the function with the following block:
var apiInstance = new CloudmersiveImageApiClient.ConvertApi();var quality = 56; // Number | Set the JPEG quality level; lowest quality is 1 (highest compression), highest quality (lowest compression) is 100; recommended value is 75var 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.convertToJpg(quality, imageFile, callback);
After that, you’re all done. Just make sure to test out quality values to find the right degree of compression for your file.