> ## Documentation Index
> Fetch the complete documentation index at: https://www.ayrshare.com/docs/llms.txt
> Use this file to discover all available pages before exploring further.

# 生成替代文字

> 为图片创建 AI 生成的替代文字

export const HeaderAPI = ({noProfileKey, profileKeyRequired}) => <>
    <ParamField header="Authorization" type="string" required>
      <a href="/apis/overview#authorization">API Key</a> of the Primary Profile.
      <br />
      <br />
      Format: <code>Authorization: Bearer API_KEY</code>
    </ParamField>
    {!noProfileKey && (profileKeyRequired ? <ParamField header="Profile-Key" type="string" required>
          <a href="/apis/overview#profile-key-format">Profile Key</a> of a User Profile.
          <br />
          <br />
          Format: <code>Profile-Key: PROFILE_KEY</code>
        </ParamField> : <ParamField header="Profile-Key" type="string">
          <a href="/apis/overview#profile-key-format">Profile Key</a> of a User Profile.
          <br />
          <br />
          Format: <code>Profile-Key: PROFILE_KEY</code>
        </ParamField>)}
  </>;

export const PlansAvailable = ({plans = [], maxPackRequired}) => {
  let displayPlans = plans;
  if (plans && plans.length === 1) {
    const lowerCasePlan = plans[0].toLowerCase();
    if (lowerCasePlan === "business") {
      displayPlans = ["Launch", "Business", "Enterprise"];
    } else if (lowerCasePlan === "premium") {
      displayPlans = ["Premium", "Launch", "Business", "Enterprise"];
    }
  }
  return <Note>
Available on {displayPlans.length === 1 ? "the " : ""}
{displayPlans.join(", ").replace(/\b\w/g, l => l.toUpperCase())}{" "}
{displayPlans.length > 1 ? "plans" : "plan"}.

{maxPackRequired && <span onClick={() => window.open('https://www.ayrshare.com/docs/additional/maxpack', '_self')} className="flex items-center mt-2 cursor-pointer">
 <span className="px-1.5 py-0.5 rounded text-sm" style={{
    backgroundColor: '#C264B6',
    color: 'white',
    fontSize: '12px'
  }}>
   Max Pack required
 </span>
</span>}
</Note>;
};

<PlansAvailable plans={["premium"]} maxPackRequired={true} />

为你的图片创建 AI 生成的替代文字（alt text）。可选择生成替代文字的语言以及需要包含的关键词。

## 请求头参数

<HeaderAPI noProfileKey />

## 请求体参数

<ParamField body="url" type="string" required>
  要生成替代文字的图片 URL。必须以 `https://` 开头。支持 JPEG、PNG、GIF、WEBP 和 BMP。
</ParamField>

<ParamField body="keywords" type="array">
  生成替代文字时需要考虑的关键词或短语字符串数组。通常只会有一两个关键词被用于最终的替代文字。
</ParamField>

<ParamField body="lang" type="string">
  输出替代文字所使用的语言。使用可用的[语言代码](/iso-codes/language)之一。
</ParamField>

<RequestExample>
  ```bash cURL theme={"system"}
  curl \
  -H "Authorization: Bearer API_KEY" \
  -H 'Content-Type: application/json' \
  -d '{"url": "https://img.ayrshare.com/012/gb.jpg"}' \
  -X POST https://api.ayrshare.com/api/generate/altText
  ```

  ```javascript JavaScript theme={"system"}
  const API_KEY = "API_KEY";
  fetch("https://api.ayrshare.com/api/generate/altText", {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
          "Authorization": `Bearer ${API_KEY}`
        },
        body: JSON.stringify({
          url: "https://img.ayrshare.com/012/gb.jpg", // required
        }),
      })
        .then((res) => res.json())
        .then((json) => console.log(json))
        .catch(console.error);
  ```

  ```python Python theme={"system"}
  import requests

  payload = {'url': 'https://img.ayrshare.com/012/gb.jpg'}
  headers = {'Content-Type': 'application/json',
          'Authorization': 'Bearer API_KEY'}

  r = requests.post('https://api.ayrshare.com/api/generate/altText',
      json=payload,
      headers=headers)

  print(r.json())
  ```

  ```php PHP theme={"system"}
      $curl = curl_init();
  $data = array (
    "url" => "https://img.ayrshare.com/012/gb.jpg"
  );

  curl_setopt_array($curl, array(
    CURLOPT_URL => 'https://api.ayrshare.com/api/generate/altText',
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_ENCODING => '',
    CURLOPT_MAXREDIRS => 10,
    CURLOPT_TIMEOUT => 0,
    CURLOPT_FOLLOWLOCATION => true,
    CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
    CURLOPT_CUSTOMREQUEST => 'POST',
    CURLOPT_POSTFIELDS => http_build_query($data),
    CURLOPT_HTTPHEADER => array(
      'Authorization: Bearer API_KEY',
      'Accept-Encoding: gzip'
    ),
  ));

  $response = curl_exec($curl);
  curl_close($curl);
  echo $response;
  ```

  ```csharp C# theme={"system"}
  using System;
  using System.Net.Http;
  using System.Text;
  using System.Threading.Tasks;
  using System.Text.Json;

  class Program
  {
      // Replace 'YOUR_API_KEY' with your actual Ayrshare API key
      private const string API_KEY = "YOUR_API_KEY";
      private static readonly HttpClient client = new HttpClient();

      static async Task Main(string[] args)
      {
          string imageUrl = "https://img.ayrshare.com/012/gb.jpg";

          try
          {
              var result = await GenerateAltTextAsync(imageUrl);
              Console.WriteLine("Generated Alt Text:");
              Console.WriteLine(JsonSerializer.Serialize(result, new JsonSerializerOptions { WriteIndented = true }));
          }
          catch (Exception e)
          {
              Console.WriteLine($"An error occurred: {e.Message}");
          }
      }

      static async Task<JsonElement> GenerateAltTextAsync(string imageUrl)
      {
          var url = "https://api.ayrshare.com/api/generate/altText";
          var requestData = new { url = imageUrl };

          client.DefaultRequestHeaders.Clear();
          client.DefaultRequestHeaders.Add("Authorization", $"Bearer {API_KEY}");

          var json = JsonSerializer.Serialize(requestData);
          var content = new StringContent(json, Encoding.UTF8, "application/json");

          var response = await client.PostAsync(url, content);

          if (!response.IsSuccessStatusCode)
          {
              throw new HttpRequestException($"HTTP error! status: {response.StatusCode}");
          }

          var responseBody = await response.Content.ReadAsStringAsync();
          return JsonSerializer.Deserialize<JsonElement>(responseBody);
      }
  }
  ```
</RequestExample>

<ResponseExample>
  ```json 200: Alt Text Generated theme={"system"}
  {
      "status": "success",
      "altText": "A ghostbusters vehicle driving through a field.",
      "url": "https://img.ayrshare.com/012/gb.jpg"
  }
  ```

  ```json 500: Error with the Image File theme={"system"}
  {
    "action": "upload",
    "status": "error",
    "code": 115,
    "message": "An error occurred uploading your file, such as a timeout at the social network. Please try your post again with the /retryPost endpoint."
  }
  ```
</ResponseExample>
