How to Crop an Image to a Face (Square OR Round Crop) using Node.js
Automatically cropping photos to a face saves time in an otherwise repetitive process (like preparing multiple headshots for a website). Our Face Cropping APIs give you the option to automatically crop a square or round shape around the first face found in any given photo, and the output result can be used for a variety of purposes. Below, we’ll demonstrate how to use this API by installing the Node.js SDK & structuring an API call with ready-to-run code snippets.
Let’s begin by running the following command:
npm install cloudmersive-image-api-client --save
Now, for a square crop, let’s structure the API call using the following code & include a Cloudmersive API key for authentication (obtainable 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.FaceApi();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.faceCropFirst(imageFile, callback);
For a round crop, let’s use the following code instead, again remembering to include an API key where indicated:
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.FaceApi();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.faceCropFirstRound(imageFile, callback);
All set — no more code needed.