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

Cloudmersive
2 min readMay 27, 2019

--

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:

This will produce an output like this:

That’s it! That was easy.

--

--

Cloudmersive
Cloudmersive

Written by Cloudmersive

There’s an API for that. Cloudmersive is a leader in Highly Scalable Cloud APIs.

No responses yet