代码示例

各种编程语言和框架的完整代码示例,帮助您快速集成我们的API

JavaScript/TypeScript 示例

人脸检测示例

以下示例展示了如何使用JavaScript在浏览器或Node.js环境中调用人脸检测API:

JavaScript
// JavaScript 人脸检测示例
import axios from 'axios';

const API_KEY = 'YOUR_API_KEY';

async function detectFaces(imageUrl) {
  try {
    const response = await axios.post(
      'https://api.example.com/v1/face/detect',
      {
        image_url: imageUrl,
        return_attributes: ['age', 'gender', 'emotion']
      },
      {
        headers: {
          'Content-Type': 'application/json',
          'X-API-Key': API_KEY
        }
      }
    );
    
    console.log('检测到人脸数量:', response.data.faces.length);
    return response.data.faces;
  } catch (error) {
    console.error('人脸检测失败:', error);
    throw error;
  }
}

// 使用示例
detectFaces('https://example.com/images/photo.jpg')
  .then(faces => {
    faces.forEach((face, index) => {
      console.log(`人脸 ${index + 1}:`);
      console.log(`  - 位置: ${JSON.stringify(face.face_rectangle)}`);
      console.log(`  - 年龄: ${face.attributes.age.value}`);
      console.log(`  - 性别: ${face.attributes.gender.value}`);
      console.log(`  - 情绪: ${face.attributes.emotion.value}`);
    });
  })
  .catch(error => {
    console.error('处理过程中出错:', error);
  });

完整集成示例

这个示例演示了如何创建一个完整的JavaScript API客户端类,包含多种API调用、错误处理和统一接口。

JavaScript
// 完整的JavaScript集成示例
// 包含身份验证、错误处理和多种API调用

class OpenAPIClient {
  constructor(apiKey) {
    this.apiKey = apiKey;
    this.baseUrl = 'https://api.example.com/v1';
    this.client = axios.create({
      baseURL: this.baseUrl,
      headers: {
        'Content-Type': 'application/json',
        'X-API-Key': this.apiKey
      }
    });
    
    // 添加响应拦截器用于错误处理
    this.client.interceptors.response.use(
      response => response,
      error => this._handleError(error)
    );
  }
  
  // 错误处理方法
  _handleError(error) {
    if (error.response) {
      // 服务器返回错误
      const status = error.response.status;
      const message = error.response.data.message || '未知错误';
      
      switch (status) {
        case 400:
          throw new Error(`参数错误: ${message}`);
        case 401:
          throw new Error('身份验证失败: API密钥无效或已过期');
        case 404:
          throw new Error(`资源不存在: ${message}`);
        case 429:
          throw new Error('请求频率超限: 请降低请求速率或升级套餐');
        default:
          throw new Error(`服务器错误 (${status}): ${message}`);
      }
    } else if (error.request) {
      // 请求已发送但没有收到响应
      throw new Error('无法连接到API服务器,请检查网络连接');
    } else {
      // 设置请求时发生错误
      throw new Error(`请求配置错误: ${error.message}`);
    }
  }
  
  // 人脸检测
  async detectFaces(imageUrl, returnAttributes = ['age', 'gender', 'emotion']) {
    const response = await this.client.post('/face/detect', {
      image_url: imageUrl,
      return_attributes: returnAttributes
    });
    return response.data;
  }
  
  // 人脸比对
  async compareFaces(imageUrl1, imageUrl2) {
    const response = await this.client.post('/face/compare', {
      image_url1: imageUrl1,
      image_url2: imageUrl2
    });
    return response.data;
  }
  
  // 3D重建
  async reconstruct3D(imageUrls, quality = 'medium') {
    const response = await this.client.post('/3d/reconstruct', {
      image_urls: imageUrls,
      quality: quality
    });
    return response.data;
  }
}

// 使用示例
async function main() {
  try {
    const client = new OpenAPIClient('YOUR_API_KEY');
    
    // 1. 检测人脸
    console.log('正在检测人脸...');
    const detectResult = await client.detectFaces('https://example.com/images/photo.jpg');
    console.log(`检测到 ${detectResult.faces.length} 个人脸`);
    
    // 2. 比对两张人脸
    console.log('\n正在比对人脸...');
    const compareResult = await client.compareFaces(
      'https://example.com/images/person1.jpg',
      'https://example.com/images/person2.jpg'
    );
    console.log(`人脸相似度: ${compareResult.confidence}%`);
    
    // 3. 3D重建
    console.log('\n正在进行3D重建...');
    const reconstructResult = await client.reconstruct3D([
      'https://example.com/images/object1.jpg',
      'https://example.com/images/object2.jpg',
      'https://example.com/images/object3.jpg'
    ]);
    console.log(`3D模型ID: ${reconstructResult.model_id}`);
    console.log(`下载链接: ${reconstructResult.download_url}`);
    
  } catch (error) {
    console.error('错误:', error.message);
  }
}

main();

提示

您可以扩展这个客户端类来包含更多的API方法,或者根据您的需求自定义错误处理逻辑。

Python 示例

人脸检测示例

以下示例展示了如何使用Python调用人脸检测API:

Python
# Python 人脸检测示例
import requests
import json

API_KEY = 'YOUR_API_KEY'
API_URL = 'https://api.example.com/v1/face/detect'

def detect_faces(image_url):
    """
    使用API检测图像中的人脸
    
    Args:
        image_url (str): 图像的URL地址
        
    Returns:
        list: 检测到的人脸列表
    """
    headers = {
        'Content-Type': 'application/json',
        'X-API-Key': API_KEY
    }
    
    payload = {
        'image_url': image_url,
        'return_attributes': ['age', 'gender', 'emotion']
    }
    
    try:
        response = requests.post(API_URL, headers=headers, json=payload)
        response.raise_for_status()  # 如果响应状态码不是2xx,引发异常
        
        result = response.json()
        print(f"检测到人脸数量: {len(result['faces'])}")
        return result['faces']
    
    except requests.exceptions.RequestException as e:
        print(f"请求错误: {e}")
        return None

# 使用示例
if __name__ == "__main__":
    image_url = "https://example.com/images/photo.jpg"
    faces = detect_faces(image_url)
    
    if faces:
        for i, face in enumerate(faces):
            print(f"人脸 {i+1}:")
            print(f"  - 位置: {face['face_rectangle']}")
            print(f"  - 年龄: {face['attributes']['age']['value']}")
            print(f"  - 性别: {face['attributes']['gender']['value']}")
            print(f"  - 情绪: {face['attributes']['emotion']['value']}")

PHP 示例

人脸检测示例

以下示例展示了如何使用PHP调用人脸检测API:

HTML
<?php
// PHP 人脸检测示例

// 设置API密钥和URL
$apiKey = 'YOUR_API_KEY';
$apiUrl = 'https://api.example.com/v1/face/detect';

/**
 * 检测图像中的人脸
 * 
 * @param string $imageUrl 图像的URL地址
 * @return array|null 检测结果或null(如果出错)
 */
function detectFaces($imageUrl) {
    global $apiKey, $apiUrl;
    
    $data = [
        'image_url' => $imageUrl,
        'return_attributes' => ['age', 'gender', 'emotion']
    ];
    
    $options = [
        'http' => [
            'header' => "Content-Type: application/json\r\n" .
                        "X-API-Key: {$apiKey}\r\n",
            'method' => 'POST',
            'content' => json_encode($data)
        ]
    ];
    
    $context = stream_context_create($options);
    
    try {
        $result = file_get_contents($apiUrl, false, $context);
        if ($result === FALSE) {
            echo "API请求失败\n";
            return null;
        }
        
        $response = json_decode($result, true);
        echo "检测到人脸数量: " . count($response['faces']) . "\n";
        return $response['faces'];
    } catch (Exception $e) {
        echo "发生错误: " . $e->getMessage() . "\n";
        return null;
    }
}

// 使用示例
$imageUrl = 'https://example.com/images/photo.jpg';
$faces = detectFaces($imageUrl);

if ($faces) {
    foreach ($faces as $index => $face) {
        echo "人脸 " . ($index + 1) . ":\n";
        echo "  - 位置: " . json_encode($face['face_rectangle']) . "\n";
        echo "  - 年龄: " . $face['attributes']['age']['value'] . "\n";
        echo "  - 性别: " . $face['attributes']['gender']['value'] . "\n";
        echo "  - 情绪: " . $face['attributes']['emotion']['value'] . "\n";
    }
}
?>

Web应用集成

Web应用集成最佳实践

以下是在Web应用程序中集成我们API的最佳实践和注意事项。

前后端分离架构

出于安全考虑,避免在前端直接调用API,而是通过您自己的后端服务进行API调用,这样可以保护您的API密钥。

客户端上传图像

如果需要处理用户上传的图像,先将图像上传到您的服务器或云存储,然后使用图像URL调用API。

加载状态处理

API调用可能需要一些时间,特别是处理大图像或复杂操作时。确保在UI中显示适当的加载状态,提高用户体验。

错误处理

实现全面的错误处理机制,为用户提供清晰的错误消息,并在可能的情况下提供恢复建议。

需要更多帮助?

如果您需要更多示例或有特定的集成问题,请联系我们的技术支持团队。