How to crop an image to the face using C# in .NET Framework
2 min readOct 2, 2019
Automatic image cropping can save you a ton of time, but setting it up manually can be difficult if you lack experience in training an AI. Thankfully there is a shortcut, which we will be exploring today. Let’s get started.
First, install the API client we will be using via NuGet:
Install-Package Cloudmersive.APIClient.NET.ImageRecognition -Version 1.3.5
Now we can call either of two functions depending on whether we want a round or square cropped image: FaceCropFirstRound and FaceCropFirst, respectively. In this example we will be using the round option:
using System;
using System.Diagnostics;
using Cloudmersive.APIClient.NET.ImageRecognition.Api;
using Cloudmersive.APIClient.NET.ImageRecognition.Client;
using Cloudmersive.APIClient.NET.ImageRecognition.Model;namespace Example
{
public class FaceCropFirstRoundExample
{
public void main()
{
// Configure API key authorization: Apikey
Configuration.Default.AddApiKey("Apikey", "YOUR_API_KEY");
// Uncomment below to setup prefix (e.g. Bearer) for API key, if needed
// Configuration.Default.AddApiKeyPrefix("Apikey", "Bearer");var apiInstance = new FaceApi();
var imageFile = new System.IO.Stream(); // System.IO.Stream | Image file to perform the operation on. Common file formats such as PNG, JPEG are supported.try
{
// Crop image to face (round)
byte[] result = apiInstance.FaceCropFirstRound(imageFile);
Debug.WriteLine(result);
}
catch (Exception e)
{
Debug.Print("Exception when calling FaceApi.FaceCropFirstRound: " + e.Message );
}
}
}
}
Done! Let’s look at an example using this image:
And here is the resulting circle-cropped image: