How to crop an image to the face in Java

This tutorial will cover how to quickly set up automated facial cropping using Java. This can be applied to anything from creating profile pictures to photo apps. We will be using a Cloudmersive API to get going in just a couple minutes.

First we set up references in the Maven POM file so that we can use Jitpack to compile the library that we will be using. Here are the code snippets we will need for this:

<repositories>
<repository>
<id>jitpack.io</id>
<url>https://jitpack.io</url>
</repository>
</repositories>

And:

<dependencies>
<dependency>
<groupId>com.github.Cloudmersive</groupId>
<artifactId>Cloudmersive.APIClient.Java</artifactId>
<version>v2.75</version>
</dependency>
</dependencies>

Lastly, we call faceCropFirst for a square crop or faceCropFirstRound for round:

// Import classes://import com.cloudmersive.client.invoker.ApiClient;//import com.cloudmersive.client.invoker.ApiException;//import com.cloudmersive.client.invoker.Configuration;//import com.cloudmersive.client.invoker.auth.*;//import com.cloudmersive.client.FaceApi;ApiClient defaultClient = Configuration.getDefaultApiClient();// Configure API key authorization: ApikeyApiKeyAuth Apikey = (ApiKeyAuth) defaultClient.getAuthentication("Apikey");Apikey.setApiKey("YOUR API KEY");// Uncomment the following line to set a prefix for the API key, e.g. "Token" (defaults to null)//Apikey.setApiKeyPrefix("Token");FaceApi apiInstance = new FaceApi();File imageFile = new File("/path/to/file"); // File | Image file to perform the operation on.  Common file formats such as PNG, JPEG are supported.try {byte[] result = apiInstance.faceCropFirst(imageFile);System.out.println(result);} catch (ApiException e) {System.err.println("Exception when calling FaceApi#faceCropFirst");e.printStackTrace();}

And that’s really all there is to it. Below is an example result for this image:

Image for post
Image for post

And the resulting round 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