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