Back to Home

AI Alt Text Generator API Documentation - Automatically Generate Alt Text for Images

Overview

The AI Alt Text Generator API is a powerful service designed to automatically generate descriptive alt text for images. By leveraging advanced AI, this API analyzes your images and creates meaningful, contextually relevant alt text, which is crucial for accessibility and SEO. Using an alt text generator for images like this one helps ensure your visual content is understandable by search engines. It also saves you hours of manual work and boosts your productivity.

Application Scenarios

The AI Alt Text Generator API is ideal for a variety of applications where generating alt text for images is essential:

API Keys

To access the AI Alt Text Generator API, you must first obtain a valid API key. This key is used to authenticate your requests and ensure secure access to the API.

Obtaining an API Key

  1. Access the API Keys Management Page: Log in to the system, then click your user avatar in the top-right corner. In the dropdown menu, click "Apply for API" to open the API Keys Management Page.
API for AI Alt Text Generator
  1. Create a New Key: Click "Create New Key", enter a name for your key in the pop-up dialog, and then click "Create".
API Keys for AI Alt Text Generator
  1. Copy and Store Your Key: Note that the key will only be displayed in full once. Click the copy icon to copy the key to your clipboard, and then click "Confirm" to close the dialog.

Important: Do not share it with others or expose it in the browser, client-side code, or any other insecure location. Keep your key safe to prevent unauthorized access.

API Endpoint

POST https://api.imagedescriber.app/api/v1/generate_alt_text

Request Parameters

Request Headers

HeaderTypeRequiredDescription
content-typestringYes`application/json`
authorizationstringYes`Bearer ${api_key}`, where `${api_key}` is your API key.

Request Body

The AI Alt Text Generator API accepts the following request structure:

{
  "image": "data:image/jpeg;base64,{image_base64_data}",
  "lang": "en"
}
ParameterTypeRequiredDescription
imagestringYes

The Base64 encoded data of the image. Supported image formats are listed in Image Format Details.

langstringNoThe language code for the returned alt text. Defaults to `en` (English). Supported language codes are listed below.

Supported Languages

CodeLanguage
enEnglish (Default)
deGerman
zhChinese
frFrench
esSpanish
jaJapanese
koKorean
itItalian
ptPortuguese
arArabic
nlDutch
plPolish

Request Example (cURL)

curl --location 'https://api.imagedescriber.app/api/v1/generate_alt_text' \
--header 'content-type: application/json' \
--header 'authorization: Bearer your_api_key' \
--data '{
    "image":"data:image/jpeg;base64,/9j/4AAQSkZJRgABAQE...",
    "lang":"en"
}'

Request Example (Python)

import requests
import base64

def image_to_base64(image_path):
    """Convert image to Base64 encoding"""
    with open(image_path, "rb") as image_file:
        encoded_string = base64.b64encode(image_file.read()).decode("utf-8")
    return encoded_string

def generate_alt_text(api_key, image_path, lang="en"):
    """Generate alt text for an image using the AI Alt Text Generator API"""
    url = "https://api.imagedescriber.app/api/v1/generate_alt_text"
    headers = {
        "content-type": "application/json",
        "authorization": f"Bearer {api_key}"
    }

    image_base64_data = image_to_base64(image_path)
    payload = {
        "image": f"data:image/jpeg;base64,{image_base64_data}",
        "lang": lang
    }

    response = requests.post(url, headers=headers, json=payload)

    if response.status_code == 200:
        result = response.json()
        alt_text_data = result["data"]["alt_text"]
        print("Generated Description:", alt_text_data["description"])
        print("Generated Alt Texts:", alt_text_data["alt"])
        print("Credits Remaining:", result["data"]["credits"]["remaining"])
    else:
        print(f"Error: {response.status_code}")
        print(response.text)

# Example usage
api_key = "your_api_key"
image_path = "your_image.jpg"

generate_alt_text(api_key, image_path)

Request Example (Next.js)

import fs from 'fs';

// Server-side implementation
const buffer = await fs.readFileSync("/temp/test.jpg");
const base64Image = buffer.toString('base64');
const imageData = `data:image/jpeg;base64,${base64Image}`;

// Client-side implementation
const file: File = /* file from input or drop event */;
const arrayBuffer = await file.arrayBuffer();
const bytes = new Uint8Array(arrayBuffer);
const base64Image = btoa(String.fromCharCode.apply(null, bytes as any));
const imageData = `data:${file.type};base64,${base64Image}`;

const body = {
  "image": imageData,
  "lang": "en"
};

const response = await fetch('https://api.imagedescriber.app/api/v1/generate_alt_text', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json',
    'Authorization': 'Bearer {your_api_key}'
  },
  body: JSON.stringify(body),
});

const result = await response.json();
console.log('Generated Description:', result.data.alt_text.description);
console.log('Generated Alt Texts:', result.data.alt_text.alt);

Response

Response Body (JSON Response)

The alt text generator for images returns a response containing a detailed description and an array of alt text options.

{
  "code": 0,
  "message": "success",
  "request_id": "unique_request_id_string",
  "data": {
    "alt_text": {
      "description": "Detailed image description",
      "alt": [
        "alt1",
        "alt2",
        "..."
      ]
    },
    "credits": {
      "amount": "credits consumed by this call",
      "remaining": "total credits remaining after this call"
    }
  }
}
FieldTypeDescription
codenumberStatus code, `0` indicates success, non-`0` indicates an error.
messagestringStatus message, describes the status of the request.
request_idstringUnique request ID, used for tracking and troubleshooting.
dataobjectContains the response data.
data.alt_textobjectContains the generated description and alt text.
data.alt_text.descriptionstringA detailed description of the image content.
data.alt_text.altarrayAn array of generated alt text strings for the image.
data.creditsobjectInformation about credit consumption and remaining balance.
data.credits.amountnumberNumber of credits consumed by this API call.
data.credits.remainingnumberTotal credits remaining in your account after this call.

Request Limits

To ensure service stability and fairness, each API key is limited to 30 requests per minute (1800 requests per hour). Requests exceeding this limit will be rejected with error code 1004.

Credit System

How to Get More Credits?

You can visit the Credit Recharge Page to purchase credit packages to support more API calls. We offer various packages to meet the needs of different users.

Error Handling

The following table lists common error codes, their meanings, and solutions:

Error CodeDescriptionSolution
1002UnauthorizedPlease verify that your `authorization` header is set correctly.
1003Invalid API KeyPlease verify that your API key is correct or obtain a new one.
1004Too Many RequestsPlease reduce your request frequency, maximum 30 requests per minute.
1005Invalid ParametersPlease verify that your request parameters conform to the specifications.
2002Insufficient Credits
2003Content Blocked by FilterPlease modify your image to ensure the content complies with regulations.
2004Invalid Image Format

Please use a supported image format, refer to Image Format Details.

2005Image Upload FailedPlease verify that your image data is valid or try uploading again later.
2006Failed to parse AI response into expected JSON format.
5050Internal Server ErrorPlease contact our technical support team and provide the `request_id`.

Image Format Details

Currently supported image formats include: JPG, JPEG, PNG, WebP. The maximum image size is 4MB.

Best Practices for Generating Alt Text

  • High Resolution: Use clear, high-resolution images for a more accurate alt text generator for images.
  • Good Lighting: Well-lit images produce more accurate and descriptive alt text.
  • Clear Subject: Images with distinct subjects and objects generate more relevant alt text.
  • Supported Formats: Stick to supported formats (JPG, PNG, WebP) for optimal results.

Use Cases and Integration Examples

SEO Enhancement

Use the AI Alt Text Generator API to automatically generate alt text for images on your website:

// Enhance image SEO with AI-generated alt text
const enhanceImageSEO = async (imageElement, apiKey) => {
  const canvas = document.createElement('canvas');
  const ctx = canvas.getContext('2d');
  canvas.width = imageElement.width;
  canvas.height = imageElement.height;
  ctx.drawImage(imageElement, 0, 0);

  const base64Image = canvas.toDataURL('image/jpeg');

  const response = await fetch('/api/v1/generate_alt_text', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      'Authorization': `Bearer ${apiKey}`
    },
    body: JSON.stringify({ image: base64Image })
  });

  const result = await response.json();
  const { alt } = result.data.alt_text;

  // Update image alt attribute for SEO and accessibility
  if (alt && alt.length > 0) {
    imageElement.alt = alt[0];
  }
};

Content Management Integration

Integrate the alt text generator for images into your CMS workflow:

# Bulk process images in a content management system
import os
import requests
from pathlib import Path

def bulk_generate_alt_text(directory_path, api_key):
    """Process all images in a directory to generate alt text"""
    image_extensions = ['.jpg', '.jpeg', '.png', '.webp']

    for image_path in Path(directory_path).iterdir():
        if image_path.suffix.lower() in image_extensions:
            try:
                # Generate alt text for each image
                result = generate_alt_text(api_key, str(image_path))

                # Save metadata to accompanying file
                metadata_path = image_path.with_suffix('.json')
                with open(metadata_path, 'w') as f:
                    json.dump(result['data']['alt_text'], f, indent=2)

                print(f"Processed: {image_path.name}")

            except Exception as e:
                print(f"Error processing {image_path.name}: {e}")

# Usage
bulk_generate_alt_text("/path/to/images", "your_api_key")

Contact Us

If you have any questions or suggestions about our AI Alt Text Generator API, please feel free to contact us through the following methods:

Start using the AI Alt Text Generator API now and unlock the power of automated image accessibility and SEO!