How to crop an image to the face using C# in .NET Framework

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:

Image for post
Image for post

And here is the resulting circle-cropped image:

Image for post
Image for post

Written by

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

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