Last updated: February 4, 2025

<span aria-hidden="true" id="face-blur-automation-protect-privacy-with-aws--net"></span>

# Face blur automation: protect privacy with AWS & .Net

![Tim Koschützki](/assets/images/teammates/avatar-tim-kos-1.jpg?dpl=dpl_57Yv8CaL8TB1QConNpNYtbZm6CfA)

**Tim Koschützki**

Co-founder · Berlin, Germany · Show bio

[](https://x.com/tim%5Fkos)[](https://github.com/tim-kos)

In today's digital world, protecting personal privacy is more important than ever. In this post, we will build a .NET application that leverages AWS Rekognition to detect faces in images, and then uses an image processing library to automatically blur those areas. This approach not only helps you comply with privacy regulations, but also integrates modern cloud-powered image analysis into your projects.

<span aria-hidden="true" id="set-up-your-net-project"></span>

## Set up your .Net project

First, create a new .NET console application. Open your terminal and run:

```bash
dotnet new console -n FaceBlurAutomation
cd FaceBlurAutomation

```

Next, add the required NuGet packages. We will use the AWS SDK (Amazon.Rekognition) for face detection and SixLabors.ImageSharp for image processing:

```bash
dotnet add package AWSSDK.Rekognition
dotnet add package SixLabors.ImageSharp --version 2.1.3

```

<span aria-hidden="true" id="understand-aws-rekognition"></span>

## Understand AWS Rekognition

AWS Rekognition offers powerful tools for image analysis. Its `DetectFaces` API returns detailed information about facial features, including bounding boxes that are relative to the image dimensions. We can use these details to locate faces and apply post-processing effects like blurring.

<span aria-hidden="true" id="implementing-face-detection-and-blurring"></span>

## Implementing face detection and blurring

Below is a complete C# example that loads an image, detects faces, and blurs each detected region using ImageSharp:

```csharp
using System;
using System.Collections.Generic;
using System.IO;
using System.Threading.Tasks;
using Amazon.Rekognition;
using Amazon.Rekognition.Model;
using SixLabors.ImageSharp;
using SixLabors.ImageSharp.Processing;

namespace FaceBlurAutomation;

public class Program
{
    private static readonly AmazonRekognitionClient _rekognitionClient = new();

    public static async Task Main(string[] args)
    {
        try
        {
            if (args.Length < 2)
            {
                throw new ArgumentException("Usage: FaceBlurAutomation <inputImagePath> <outputImagePath>");
            }

            string inputImagePath = args[0];
            string outputImagePath = args[1];

            if (!File.Exists(inputImagePath))
            {
                throw new FileNotFoundException("Input image file not found", inputImagePath);
            }

            await ProcessImageAsync(inputImagePath, outputImagePath);
            Console.WriteLine($"Processed image saved to {outputImagePath}");
        }
        catch (Exception ex)
        {
            Console.Error.WriteLine($"Error: {ex.Message}");
            Environment.Exit(1);
        }
    }

    private static async Task ProcessImageAsync(string inputPath, string outputPath)
    {
        byte[] imageBytes = await File.ReadAllBytesAsync(inputPath);
        var detectRequest = new DetectFacesRequest
        {
            Image = new Amazon.Rekognition.Model.Image
            {
                Bytes = new MemoryStream(imageBytes)
            },
            Attributes = new List<string> { "DEFAULT" }
        };

        var detectResponse = await _rekognitionClient.DetectFacesAsync(detectRequest);

        if (!detectResponse.FaceDetails.Any())
        {
            Console.WriteLine("No faces detected in the image");
            File.Copy(inputPath, outputPath, true);
            return;
        }

        using var image = await Image.LoadAsync(inputPath);
        foreach (var faceDetail in detectResponse.FaceDetails)
        {
            var box = faceDetail.BoundingBox;
            var faceRegion = new Rectangle(
                (int)(box.Left * image.Width),
                (int)(box.Top * image.Height),
                (int)(box.Width * image.Width),
                (int)(box.Height * image.Height));

            image.Mutate(ctx => ctx.GaussianBlur(10, faceRegion));
        }

        await image.SaveAsync(outputPath);
    }
}

```

<span aria-hidden="true" id="how-it-works"></span>

### How it works

1. We load the image into a byte array and pass it to AWS Rekognition's `DetectFacesAsync` method.
2. Rekognition returns a list of face details, each containing a normalized bounding box for the detected face region.
3. We load the same image using ImageSharp and iterate over these bounding boxes, converting them from normalized coordinates to actual pixel values.
4. For each face, we apply a Gaussian blur to the specified region, effectively anonymizing the faces.
5. Finally, we save the processed image to disk.

<span aria-hidden="true" id="error-handling-and-testing"></span>

## Error handling and testing

The example includes error handling for common scenarios:

* Missing or invalid command-line arguments
* Non-existent input files
* AWS service errors
* Image processing failures
* Cases where no faces are detected

For production environments, consider adding:

```csharp
try
{
    // AWS operations
}
catch (AmazonRekognitionException ex)
{
    // Handle AWS-specific errors
    logger.LogError($"AWS Rekognition error: {ex.Message}");
}
catch (ImageProcessingException ex)
{
    // Handle image processing errors
    logger.LogError($"Image processing error: {ex.Message}");
}

```

<span aria-hidden="true" id="extend-your-application"></span>

## Extend your application

This basic example can be extended in various ways:

* Integrate with a web API to process images uploaded by users.
* Use a storage service such as Amazon S3 for input and output images.
* Combine this technique with other image analysis tools to create a comprehensive privacy protection suite.

<span aria-hidden="true" id="summary"></span>

## Summary

You have now built a .NET application that leverages AWS Rekognition to detect faces and applies a blur effect to safeguard privacy. This approach demonstrates how to integrate cloud-based image analysis with modern .NET libraries to address real-world challenges.

By the way, Transloadit also leverages similar AWS image analysis techniques in its /image/describe robot to enhance image processing workflows.

\#aws-rekognition#dotnet#c-sharp#image-analysis#auto-image-processing#image-processing-service

### 👩‍💻 Join 20k+ developers

Sign up for our [monthly newsletter](/newsletters.md) to receive direct links to 3 exclusive tech — and 2 product updates. No less, no more.

Your email:

Get access

## File uploading and encoding. Made simple.

Transloadit streamlines file handling for developers, trusted by brands like Coursera and The New York Times. We’re known for a reliable API, top-notch support, and a strong commitment to open source, with projects like [Uppy⁠](https://uppy.io) and [Tus⁠](https://tus.io) setting standards in file processing.

[Sign up](/c/)[Book a Demo](https://survey.typeform.com/to/kRg47Xi5)

No credit card needed

Cancel anytime
