文檔

快速開始

在幾分鐘內開始使用 AI 圖片描述 API。本指南將帶您完成將 AI 驅動的圖片描述整合到應用程式中的基本步驟。

前提條件

在開始之前,請確保您擁有:

  • 帳戶: 在 aidescribepicture.com 註冊
  • API 金鑰: 在設定中建立 API 金鑰
  • 積分: 購買圖片描述積分
  • 圖片 URL: 用於測試的公開可存取圖片 URL

第 1 步:取得您的 API 金鑰

  1. 造訪 aidescribepicture.com
  2. 使用您的 Google 帳戶登入
  3. 導航到設定 > API 金鑰
  4. 點擊「建立新 API 金鑰」按鈕
  5. 輸入金鑰名稱(例如,「我的應用程式」)
  6. 建立金鑰後,複製完整的金鑰值(請妥善保管!)

API 金鑰格式

  • sk- 開頭
  • 包含隨機產生的字元
  • 範例:sk-abc123def456ghi789...

第 2 步:進行您的第一次 API 呼叫

使用 cURL

curl -X POST https://aidescribepicture.com/api/api-call/describe-picture \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer YOUR_API_KEY" \
  -d '{
    "imageUrl": "https://example.com/image.jpg",
    "prompt": "詳細描述這張圖片"
  }'

使用 JavaScript

async function describeImage(imageUrl, apiKey, prompt = null) {
  try {
    const response = await fetch('https://aidescribepicture.com/api/api-call/describe-picture', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${apiKey}`
      },
      body: JSON.stringify({
        imageUrl: imageUrl,
        prompt: prompt
      })
    });
 
    if (!response.ok) {
      const error = await response.text();
      throw new Error(`API 錯誤: ${response.status} - ${error}`);
    }
 
    const result = await response.json();
    
    // 提取描述內容
    const description = result.choices[0].message.content;
    return description;
  } catch (error) {
    console.error('描述圖片時發生錯誤:', error);
    throw error;
  }
}
 
// 使用範例
const description = await describeImage(
  'https://example.com/image.jpg',
  'your-api-key-here',
  '詳細描述這張圖片'
);
console.log('圖片描述:', description);

第 3 步:處理回應

API 回傳包含圖片描述的 JSON 回應:

{
  "choices": [
    {
      "message": {
        "content": "這張圖片顯示了一隻紅狐狸的特寫,它正對著鏡頭。狐狸有蓬鬆的橘色和白色毛髮,以及豎立的耳朵和炯炯有神的棕色眼睛。背景是模糊的,可能是在雪地裡或一個明亮的環境中。"
      }
    }
  ]
}

choices[0].message.content 欄位包含實際的圖片描述文字。

第 4 步:顯示結果

在 HTML 中

<div id="description">
  <p id="image-description"></p>
</div>

在 JavaScript 中

// 顯示描述
const descriptionElement = document.getElementById('image-description');
descriptionElement.textContent = description;

第 5 步:錯誤處理

始終實作適當的錯誤處理:

try {
  const description = await describeImage(imageUrl, apiKey, prompt);
  // 處理成功
  console.log('描述:', description);
} catch (error) {
  if (error.message.includes('401')) {
    console.error('無效的 API 金鑰');
  } else if (error.message.includes('402')) {
    console.error('積分不足');
  } else if (error.message.includes('429')) {
    console.error('超出速率限制');
  } else {
    console.error('API 錯誤:', error.message);
  }
}

API 金鑰管理

在設定中管理金鑰

  • 檢視所有 API 金鑰清單
  • 檢視金鑰使用統計
  • 停用或刪除未使用的金鑰
  • 檢視金鑰的最後使用時間

安全最佳實踐

  • 永遠不要在用戶端程式碼中硬編碼 API 金鑰
  • 使用環境變數儲存金鑰
  • 定期輪換 API 金鑰
  • 為不同環境使用不同的金鑰

環境變數範例

# .env 檔案
IMAGE_DESCRIPTION_API_KEY=sk-your-api-key-here
// 在程式碼中使用
const apiKey = process.env.IMAGE_DESCRIPTION_API_KEY;