Scan and block sensitive photos in Java

While user submissions can provide some great content, there are obviously some issues that come along with it. Perhaps the most difficult of these problems to deal with is that of racy photos, potentially causing damage to your brand image and even getting your content flagged by search engines. Today we will be looking at how to quickly remove this thorn from your side so you can get back to the important stuff. Let’s dive in.

The first thing to do is add references in your Maven POM file. Let’s start with the repository:

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

Then a reference to the dependency:

<dependencies>
<dependency>
<groupId>com.github.Cloudmersive</groupId>
<artifactId>Cloudmersive.APIClient.Java</artifactId>
<version>v2.32</version>
</dependency>
</dependencies>

Lastly, we call nsfwClassify and give an imageFile to work with:

// 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.NsfwApi;
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");
NsfwApi apiInstance = new NsfwApi();
File imageFile = new File("/path/to/file"); // File | Image file to perform the operation on. Common file formats such as PNG, JPEG are supported.
try {
NsfwResult result = apiInstance.nsfwClassify(imageFile);
System.out.println(result);
} catch (ApiException e) {
System.err.println("Exception when calling NsfwApi#nsfwClassify");
e.printStackTrace();
}

And it’s just that easy! Let’s try it out on this example photo:

Image for post
Image for post

Here are the results:

{
"Successful": true,
"Score": 0.327357530594,
"ClassificationOutcome": "SafeContent_ModerateProbability"
}

As you can see we are given a score between 0 and 1 as well as a general classification.

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