Checking Adult Images with Microsoft Azure Cognitive Services and JavaScript

Microsoft Azure Cognitive Services offers a variety of APIs, including the Computer Vision API, which can be used to analyze images, including adult content detection. To use this service with JavaScript, you can make HTTP requests to the API endpoint. Here’s a basic example using JavaScript and the Fetch API:

  1. Get Azure Cognitive Services API Key:
    • First, you need to sign up for Azure Cognitive Services and create a Computer Vision resource.
    • Obtain the API key associated with your resource.
  2. Use the Fetch API in JavaScript:
    • You can use the Fetch API to send HTTP requests. Here’s an example:
const apiKey = 'YOUR_AZURE_COGNITIVE_SERVICES_API_KEY';
const endpoint = 'https://your-cv-api.cognitiveservices.azure.com/vision/v3.1/analyze'; // Replace with your API endpoint

function checkAdultContent(imageUrl) {
    const params = {
        visualFeatures: 'Adult',
        details: '',
        language: 'en',
    };

    const apiUrl = new URL(endpoint);
    apiUrl.searchParams.append('visualFeatures', params.visualFeatures);
    apiUrl.searchParams.append('details', params.details);
    apiUrl.searchParams.append('language', params.language);

    fetch(apiUrl.toString(), {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
            'Ocp-Apim-Subscription-Key': apiKey,
        },
        body: JSON.stringify({ url: imageUrl }),
    })
        .then(response => response.json())
        .then(data => {
            // Check the results for adult content
            const adultContentScore = data.adult.adultScore;
            console.log('Adult Content Score:', adultContentScore);

            // You can implement your own logic based on the score
            if (adultContentScore > 0.5) {
                console.log('This image may contain adult content.');
            } else {
                console.log('This image does not contain adult content.');
            }
        })
        .catch(error => {
            console.error('Error:', error);
        });
}

// Example usage
const imageUrl = 'URL_OF_YOUR_IMAGE';
checkAdultContent(imageUrl);

Replace 'YOUR_AZURE_COGNITIVE_SERVICES_API_KEY' and 'https://your-cv-api.cognitiveservices.azure.com/vision/v3.1/analyze' with your actual API key and endpoint. Replace 'URL_OF_YOUR_IMAGE' with the URL of the image you want to check.

Please note that the above code is a basic example, and you may want to enhance it based on your specific requirements and error handling needs. Additionally, ensure that you are complying with Microsoft’s terms of service when using their Cognitive Services.

Image by starline on Freepik


Comments

Leave a Reply

Your email address will not be published. Required fields are marked *