How to crop an image to the face in Node.js

For this task, we want to take an arbitrary input image, locate the face, and then crop that image to the face. This can be useful for creating profile pictures for websites, loyalty programs, and so on.

The first step is to add a reference to the library:

"dependencies": {
"cloudmersive-image-api-client": "^1.1.4"
}

Then, we just need to call the faceCropFirst method to crop to a square around the face of the user in the input image:

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);

If we want a circular crop instead of a square crop for stylistic reasons, we can take advantage of the method instead:

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);

Here is an example input:

Image for post
Image for post

This will produce an output like this:

Image for post
Image for post

That’s it! That was easy.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store