DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Related

  • Building Meeting Audio RAG on Microsoft Foundry With Fast Transcription and Foundry IQ
  • Prompt, Fine-Tune, or Compile: The Three Ways to Build Anything in AI
  • Why Is the Agent Card Important?
  • AI-Powered API Development With Spring AI

Trending

  • Beyond JSON: Benchmarking TOON and TOON-LD for LLMs
  • Why DAST Findings Are Hard to Fix and How to Make Them Actionable
  • Deploying an Enterprise LLM Chatbot on Databricks With RAG, MLflow, Vector Search, and Model Serving
  • Reliability Without Control: Operating SRE Practices in Platform–SaaS and API-Dependent Systems
  1. DZone
  2. Data Engineering
  3. AI/ML
  4. How to Detect AI-Generated Images in C# Using an API

How to Detect AI-Generated Images in C# Using an API

Build a C# workflow that analyzes uploaded images for signs of AI generation and turns the returned risk score into a practical application decision.

By 
Brian O'Neill user avatar
Brian O'Neill
DZone Core CORE ·
Sep. 01, 26 · Analysis
Likes (0)
Comment
Save
Tweet
Share
98 Views

Join the DZone community and get the full member experience.

Join For Free

When someone uploads an image to your application, it might look perfectly fine at first glance. It might open correctly, pass file validation, and avoid triggering any obvious red flags. But that still doesn’t necessarily mean the file is trustworthy.

In modern systems, especially marketplaces, identity verification flows, insurance submissions, academic portals, and editorial pipelines, how an image was created can matter just as much as what that image shows. A synthetic, AI-generated image can be technically valid and "safe" while still being completely inappropriate for the context in which it’s used.

AI image detection offers your system a way to make better decisions about the content it accepts. It's not a final authority; rather, it's a form of content moderation that ensures you have clear visibility into and governance over the content you process and share.

In this article, we’ll walk through why AI detection is challenging, how to design a practical workflow around it, and how to implement AI image analysis in C# using an image recognition API.

Why AI Image Detection is Difficult

You might've noticed that the quality of AI-generated images has improved dramatically in recent years. The early giveaways (extra fingers, warped text, strange lighting, etc.) are becoming less common. If you ask strangers on the street to pick out AI-generated images from a lineup of otherwise authentic photos, you're unlikely to get a consistent answer.

That's because today's generative models are designed to mimic real-world photography and illustration patterns. That means even a perfectly normal-looking image might still be synthetic, and a slightly odd-looking image might still be completely real.

This creates a considerable challenge. We live in a world where there's no single visual feature that reliably, reproducibly separates real from synthetically generated content. A bit unnerving, right?

Metadata doesn’t always solve the problem either. While images can contain useful provenance information, that often gets stripped out during editing, compression, or platform uploads. Even something as simple as re-saving an image can remove the original creation context entirely. And of course, it's trivial to change file names without affecting the underlying pixels, so you're unlikely to catch anyone red-handed with an AI platform staring you in the face.

Because of this, modern AI detection systems rely instead on probabilistic models. Instead of saying “this image is AI-generated,” they try to estimate how likely that is to be the case based on learned patterns from large datasets of real and synthetic images.

There's an important distinction to make here: in AI detection, we’re looking for confidence rather than absolute truth. If we want to benefit from AI detection services, it's essential that we embrace their uncertainty.

Here's what that means in practice: high confidence scores justify content review or restriction, mid-range scores indicate uncertainty, and low scores reduce concern but do not guarantee authenticity. AI detection works best as one layer in a broader content validation strategy.

Designing a Practical Detection Workflow

Before thinking about how to invoke an AI detection service, which we'll look at later in this article, it’s useful to step back and consider where it fits within a broader image-handling workflow.

In practice, AI detection is just one stage in a normal pipeline that begins the moment a user submits an image. As we'll see in our demonstration later on, the service handling AI detection might be exposed as an API, but it could just as easily be a background job, a message queue consumer, or even an internal library call if you're ambitious about building internal tools. The important idea isn't how you invoke that service, but when and why it gets called in your system.

A typical content upload workflow starts with basic validation. That means checking whether a file is present and readable, whether the format is supported (such as JPEG or PNG), whether the file size falls within acceptable limits, and whether the actual file type matches its extension.

These checks are important because they protect your system from malformed or malicious inputs before any deeper analysis happens. That's not unique to the AI detection topic, of course, but it's critical nonetheless.

Once a file is validated, the next step is normalization. In this case, the idea isn't to alter the image content; rather, it's to standardize how the image is handled as it moves through the system. The goal here is to maintain consistency regardless of how the detection service is implemented. This includes keeping the original image data intact, passing it through a stream, buffer, or temporary storage layer, and ensuring the data is correctly positioned and accessible for downstream processing.

This matters because even small transformations like resizing or re-encoding can change the very signals you’re trying to analyze.  So, in most analysis workflows (that is, pipelines that prioritize preserving signal integrity), you should defer any modification unless it's explicitly required.

At this point, the image is finally ready to be evaluated by an AI detection system. This evaluation can be triggered through your existing processing pipeline, using whichever execution model your system is already built around. Regardless of the mechanism, the role of the detection step is the same: produce a structured assessment of whether the image is likely to be AI-generated or manipulated.

From there, your application can apply its own business rules. There isn't a "one size fits all" way to do this: the exact thresholds for AI detection should always reflect your use case. For example, a social media avatar and a legal document shouldn't necessarily be treated the same way; there's a bit more at stake if the latter is fabricated.

Where AI Image Detection Fits in an Application

AI image detection should run as early as possible in your content ingestion pipeline.  That means at upload, submission, or intake; sometime before content is trusted or passed downstream.

There are two general scanning approaches here that make sense in different contexts: synchronous and asynchronous detection.

In synchronous detection, the system scans content right away and waits for a result before continuing. This approach is simple and provides immediate feedback, but it does add latency to the whole workflow. It’s usually best for controlled flows where users expect to get instant validation.

In asynchronous detection, images are accepted first and then analyzed in the background. This approach generally scales better, and it avoids blocking users, which makes it the ideal choice for high-volume (and especially non-urgent) workflows.  Most enterprise-scale workflows will probably be asynchronous.

Ultimately, the core rule for both approaches is the same: don’t trust the image until it's been thoroughly evaluated. 

Detecting AI-Generated Images With C#

Now that we've covered some of the biggest factors involved in detecting AI-generated images, we'll go ahead and explore one way to implement this functionality in C#. 

In this example, we'll use an image recognition API. The SDK boils the process down to two steps: submit an image and receive a structured detection result. If you’re considering other options for AI image detection, you might want to look into Hive AI Detector alternatives, CLIP-based classifiers, or locally hosted models from Hugging Face.

First, we install the package:

C#
 
Install-Package Cloudmersive.APIClient.NETCore.ImageRecognition -Version 2.2.0


Next, we import the required namespaces:

C#
 
using System;
using System.IO;
using Cloudmersive.APIClient.NETCore.ImageRecognition.Api;
using Cloudmersive.APIClient.NETCore.ImageRecognition.Client;
using Cloudmersive.APIClient.NETCore.ImageRecognition.Model;


Now we configure the API key and prepare the image stream:

C#
 
var configuration = new Configuration();
configuration.AddApiKey("Apikey", "YOUR_API_KEY");

var apiInstance = new AiImageDetectionApi(configuration);


Now we can open the image stream and call the detection endpoint:

C#
 
try
{
    using (var imageFile = new FileStream(
        @"C:\temp\input-image.png",
        FileMode.Open,
        FileAccess.Read))
    {
        ImageAiDetectionResult result =
            apiInstance.AiImageDetectionDetectFile(imageFile);

        if (result == null ||
            !result.AiGeneratedRiskScore.HasValue)
        {
            Console.WriteLine(
                "The image could not be conclusively evaluated.");
        }
        else
        {
            Console.WriteLine(
                $"Clean result: " +
                $"{result.CleanResult?.ToString() ?? "Unknown"}");

            Console.WriteLine(
                $"AI risk score: " +
                $"{result.AiGeneratedRiskScore.Value}");

            Console.WriteLine(
                $"Possible AI source: " +
                $"{result.AiSource ?? "Unknown"}");
        }
    }
}
catch (Exception e)
{
    Console.Error.WriteLine(
        "Exception when calling " +
        "AiImageDetectionApi.AiImageDetectionDetectFile: " +
        e.Message);
}


This example keeps error handling simple for clarity, but in a production system you’ll obviously want more granular handling for scenarios like invalid input, network failures, API rate limits, etc.

Note that a failed detection should never silently pass the image through. It should instead result in a clear “unverified” or “pending review” state (or something similar).

Interpreting the Detection Result

You get three response fields:

CleanResult is a quick yes/no check. true means no AI-generated content was detected; false means there might be a match. This result is based on the risk score.

AiGeneratedRiskScore runs from 0.0 to 1.0. Higher scores mean a higher chance the content was AI-generated. Scores above 0.8 are high risk and trigger CleanResult: false.

AiSource is the final field, and it may show which specific AI content generation tool likely generated the content. It’s intended to be useful context, but it won’t always be available, so it obviously shouldn't be relied on.

Together, these give you a quick result, a risk score, and optional context. None of them is absolute proof, but they can help you make a more informed decision.

Turning the Result into an Application Decision

Once you have a risk score, you can map it to a simple decision model (that's what I would do).

Here’s one quick example of that:

C#
 
public enum ImageDecision
{
    Accept,
    ManualReview,
    Reject,
    Unverified
}

public static ImageDecision EvaluateImage(
    ImageAiDetectionResult result)
{
    if (result == null ||
        !result.AiGeneratedRiskScore.HasValue)
    {
        return ImageDecision.Unverified;
    }

    double riskScore = result.AiGeneratedRiskScore.Value;

    if (riskScore > 0.8)
    {
        return ImageDecision.Reject;
    }
    else if (riskScore > 0.5)
    {
        return ImageDecision.ManualReview;
    }
    else
    {
        return ImageDecision.Accept;
    }
}


This structure is (intentionally) simple, but the meaning behind each outcome is flexible.

For example, in a lot of real-world systems, “Reject” might actually mean "hold for review".  “ManualReview” might "trigger a human workflow", and “Accept” might still be logged for auditing.

It's also worth noting that in this example code, we aren't directly using the CleanResult response when making the decision. We are bypassing that completely, only using the risk score from the broader detection result. If you wanted to, you could inspect CleanResult as part of your application logic; for example, to distinguish between a clean result, a flagged result, or an inconclusive response. You could then use that information alongside the risk score when deciding whether to accept, review, or reject an image.

Conclusion

AI image detection doesn’t give you certainty, but it does give you something extremely valuable in today's world of increasingly indistinguishable AI content: a structured way to reason about uncertainty.

By combining file validation, careful input handling, and probabilistic AI detection, you can build workflows that are both practical and resilient.

In C#, integrating an image recognition API gives you a straightforward way to evaluate images at the point of entry, interpret risk scores flexibly, and apply consistent business rules without over-relying on one individual signal. The API approach makes sense because it keeps the recognition logic focused, reusable, and easier to update as models and requirements change, while allowing the rest of the application to work with a clear, stable interface.

The key takeaway is ultimately pretty simple: AI detection is necessary for modern content systems, but it should be treated as guidance rather than a judgment. When used judiciously, it will become a powerful part of a broader trust and verification strategy.

AI API

Opinions expressed by DZone contributors are their own.

Related

  • Building Meeting Audio RAG on Microsoft Foundry With Fast Transcription and Foundry IQ
  • Prompt, Fine-Tune, or Compile: The Three Ways to Build Anything in AI
  • Why Is the Agent Card Important?
  • AI-Powered API Development With Spring AI

Partner Resources

×

Comments

The likes didn't load as expected. Please refresh the page and try again.

  • RSS
  • X
  • Facebook

ABOUT US

  • About DZone
  • Support and feedback
  • Community research

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 215
  • Nashville, TN 37211
  • [email protected]

Let's be friends:

  • RSS
  • X
  • Facebook