How to crop an image to the face in Javascript

Smart image cropping can be a very useful feature, for example in creating profile pictures. The Deep Learning requirement for this can be a bit daunting, considering the hours of work and training time needed to get good results. We already have this set up, however, and have it packaged in a shiny API that’s all ready to go. Here’s how to use it.

First install our API client, which needs to have this script tag in your HTML file.

<script src="https://cdn.cloudmersive.com/jsclient/cloudmersive-image-client.js"></script>

And now simply call our function, as we see below. There is a also faceCropFirst, which creates a square cropped photo.

var CloudmersiveImageApiClient = require('cloudmersive-image-api-client');var defaultClient = CloudmersiveImageApiClient.ApiClient.instance;// Configure API key authorization: Apikeyvar Apikey = defaultClient.authentications['Apikey'];Apikey.apiKey = 'YOUR API KEY';// Uncomment the following line to set a prefix for the API key, e.g. "Token" (defaults to null)//Apikey.apiKeyPrefix = 'Token';var apiInstance = new CloudmersiveImageApiClient.FaceApi();var imageFile = "/path/to/file"; // 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);

OK, done. Yup, it’s really that easy. Let’s test it out on this image.

Image for post
Image for post

And the resulting cropped image.

Image for post
Image for post

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