How to Crop an Image to a Face (Square or Circle Shape) with Java

Cloudmersive
2 min readMay 10, 2022

--

Looking for an easy way to crop headshots for a website? We might just have the perfect solution. Our crop-to-face APIs can identify the location of a face within an image and automatically crop either a square or circle shape around it. To take advantage of either API using Java, follow instructions included below.

Begin by installing the Maven SDK. Add a reference to the repository in pom.xml:

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

Next, add a reference to the dependency in pom.xml:

<dependencies>
<dependency>
<groupId>com.github.Cloudmersive</groupId>
<artifactId>Cloudmersive.APIClient.Java</artifactId>
<version>v4.25</version>
</dependency>
</dependencies>

Then, add in the import classes and include the code snippets to authenticate your API key. You can get an API key by visiting our website (Home — Cloudmersive APIs) and registering a free account.

// 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: Apikey
ApiKeyAuth 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");

Now it’s time to choose the type of crop you want, and then you’re good to go. If you’re interested in performing a square crop, include this final snippet in your code:

FaceApi apiInstance = new FaceApi();
File imageFile = new File("/path/to/inputfile"); // 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 if you’re looking for a circle crop instead:

FaceApi apiInstance = new FaceApi();
File imageFile = new File("/path/to/inputfile"); // File | Image file to perform the operation on. Common file formats such as PNG, JPEG are supported.
try {
byte[] result = apiInstance.faceCropFirstRound(imageFile);
System.out.println(result);
} catch (ApiException e) {
System.err.println("Exception when calling FaceApi#faceCropFirstRound");
e.printStackTrace();
}

--

--

Cloudmersive
Cloudmersive

Written by Cloudmersive

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

No responses yet