Scan and block sensitive/NSFW photos using C# in .NET Framework

User submitted photos can be either a boon or a curse depending on the contents. Being able to filter one from the other is crucial, as NSFW photos can be very embarrassing to your company’s image. Setting up an automated system for this from scratch is a daunting prospect, involving deep learning and heaps of code. However, there is a much easier solution: use a free API instead. Today, we will be looking at how to set this up quickly and easily.

First, install Cloudmersive’s Image Recognition API client using NuGet via the Package Manager console:

Install-Package Cloudmersive.APIClient.NET.ImageRecognition -Version 1.3.5

Then call NsfwClassify with the image that needs to be evaluated.

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 NsfwClassifyExample
{
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 NsfwApi();
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
{
// Not safe for work (NSFW) racy content classification
NsfwResult result = apiInstance.NsfwClassify(imageFile);
Debug.WriteLine(result);
}
catch (Exception e)
{
Debug.Print("Exception when calling NsfwApi.NsfwClassify: " + e.Message );
}
}
}
}

Your output will look something like this:

{
"Successful": true,
"Score": 0,
"ClassificationOutcome": "string"
}

The score will be between 0 and 1, with a high score indicating higher risk of inappropriate content (.8 and above being high certainty). This same API includes a large variety of functions related to images, including facial recognition, image rotation, adding text to an image, and even age/gender detection.

Image for post
Image for post

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