

本文属于机器翻译版本。若本译文内容与英语原文存在差异，则一律以英文原文为准。

# 使用 JavaScript
<a name="image-bytes-javascript"></a>

以下 JavaScript 网页示例允许用户选择图像并查看图像中检测到的人脸的估计年龄。通过调用 [DetectFaces](https://docs.aws.amazon.com/rekognition/latest/APIReference/API_DetectFaces.html) 返回估计年龄。

使用函数加载所选图像，该 JavaScript`FileReader.readAsDataURL`函数对图像进行 base64 编码。这对于在 HTML 画布上显示图像非常有用。但这意味着，在将图像字节传递给 Amazon Rekognition Image 操作之前，必须取消对它们的编码。此示例说明如何取消对加载的图像字节的编码。如果已编码的图像字节对您没有用，请改用 `FileReader.readAsArrayBuffer`，因为加载的图像是未编码的。这意味着，无需先对图像字节取消编码即可调用 Amazon Rekognition Image 操作。有关示例，请参阅[使用 readAsArray缓冲区](#image-bytes-javascript-unencoded)。

**运行示 JavaScript 例**

1. 将示例源代码加载到编辑器中。

1. 获取 Amazon Cognito 身份池标识符。有关更多信息，请参阅 [获取 Amazon Cognito 身份池标识符](#image-bytes-javascript-auth)。

1. 在示例代码的 `AnonLog` 函数中，将 `IdentityPoolIdToUse` 和 `RegionToUse` 更改为您在[获取 Amazon Cognito 身份池标识符](#image-bytes-javascript-auth)的步骤 9 中记下的值。

1. 在 `DetectFaces` 函数中，将 `RegionToUse` 更改为您在上一步中使用的值。

1. 将示例源代码另存为一个 `.html` 文件。

1. 将此文件加载到浏览器中。

1. 选择**浏览...**按钮，并选择包含一个或多个人脸的图像。这将显示一个表，其中包含图像中检测到的每个人脸的估计年龄。

**注意**  
以下代码示例使用两个不再属于 Amazon Cognito 的脚本。要获取这些文件，请点击.min.js 和 [ aws-cognito-sdk.min.js](https://raw.githubusercontent.com/aws/amazon-cognito-identity-js/master/dist/aws-cognito-sdk.js) 的链接，然后将[ amazon-cognito-identity每个](https://raw.githubusercontent.com/aws/amazon-cognito-identity-js/master/dist/amazon-cognito-identity.min.js)文件中的文本另存为单独的文件。`.js`

## JavaScript 示例代码
<a name="image-bytes-javascript-code"></a>

以下代码示例使用 JavaScript V2。有关 JavaScript V3 中的示例，请参阅[AWS 文档 SDK 示例 GitHub 存储库中的示例。](https://github.com/awsdocs/aws-doc-sdk-examples/tree/master/javascriptv3/example_code/rekognition/estimate-age-example/src)

```
<!--
Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved.
PDX-License-Identifier: MIT-0 (For details, see https://github.com/awsdocs/amazon-rekognition-developer-guide/blob/master/LICENSE-SAMPLECODE.)
-->
<!DOCTYPE html>
<html>
<head>
  <script src="aws-cognito-sdk.min.js"></script>
  <script src="amazon-cognito-identity.min.js"></script>
  <script src="https://sdk.amazonaws.com/js/aws-sdk-2.16.0.min.js"></script>
  <meta charset="UTF-8">
  <title>Rekognition</title>
</head>

<body>
  <H1>Age Estimator</H1>
  <input type="file" name="fileToUpload" id="fileToUpload" accept="image/*">
  <p id="opResult"></p>
</body>
<script>

  document.getElementById("fileToUpload").addEventListener("change", function (event) {
    ProcessImage();
  }, false);
  
  //Calls DetectFaces API and shows estimated ages of detected faces
  function DetectFaces(imageData) {
    AWS.region = "RegionToUse";
    var rekognition = new AWS.Rekognition();
    var params = {
      Image: {
        Bytes: imageData
      },
      Attributes: [
        'ALL',
      ]
    };
    rekognition.detectFaces(params, function (err, data) {
      if (err) console.log(err, err.stack); // an error occurred
      else {
       var table = "<table><tr><th>Low</th><th>High</th></tr>";
        // show each face and build out estimated age table
        for (var i = 0; i < data.FaceDetails.length; i++) {
          table += '<tr><td>' + data.FaceDetails[i].AgeRange.Low +
            '</td><td>' + data.FaceDetails[i].AgeRange.High + '</td></tr>';
        }
        table += "</table>";
        document.getElementById("opResult").innerHTML = table;
      }
    });
  }
  //Loads selected image and unencodes image bytes for Rekognition DetectFaces API
  function ProcessImage() {
    AnonLog();
    var control = document.getElementById("fileToUpload");
    var file = control.files[0];

    // Load base64 encoded image 
    var reader = new FileReader();
    reader.onload = (function (theFile) {
      return function (e) {
        var img = document.createElement('img');
        var image = null;
        img.src = e.target.result;
        var jpg = true;
        try {
          image = atob(e.target.result.split("data:image/jpeg;base64,")[1]);

        } catch (e) {
          jpg = false;
        }
        if (jpg == false) {
          try {
            image = atob(e.target.result.split("data:image/png;base64,")[1]);
          } catch (e) {
            alert("Not an image file Rekognition can process");
            return;
          }
        }
        //unencode image bytes for Rekognition DetectFaces API 
        var length = image.length;
        imageBytes = new ArrayBuffer(length);
        var ua = new Uint8Array(imageBytes);
        for (var i = 0; i < length; i++) {
          ua[i] = image.charCodeAt(i);
        }
        //Call Rekognition  
        DetectFaces(ua);
      };
    })(file);
    reader.readAsDataURL(file);
  }
  //Provides anonymous log on to AWS services
  function AnonLog() {
    
    // Configure the credentials provider to use your identity pool
    AWS.config.region = 'RegionToUse'; // Region
    AWS.config.credentials = new AWS.CognitoIdentityCredentials({
      IdentityPoolId: 'IdentityPoolIdToUse',
    });
    // Make the call to obtain credentials
    AWS.config.credentials.get(function () {
      // Credentials will be available when this function is called.
      var accessKeyId = AWS.config.credentials.accessKeyId;
      var secretAccessKey = AWS.config.credentials.secretAccessKey;
      var sessionToken = AWS.config.credentials.sessionToken;
    });
  }
</script>
</html>
```

### 使用 readAsArray缓冲区
<a name="image-bytes-javascript-unencoded"></a>

以下代码片段是示例代码中该`ProcessImage`函数的替代实现，使用 JavaScript V2。它使用 `readAsArrayBuffer` 加载图像并调用 `DetectFaces`。由于 `readAsArrayBuffer` 不对加载的文件进行 base64 编码，因此，在调用 Amazon Rekognition Image 操作前无需取消对图像字节的编码。

```
//Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved.
//PDX-License-Identifier: MIT-0 (For details, see https://github.com/awsdocs/amazon-rekognition-developer-guide/blob/master/LICENSE-SAMPLECODE.)

function ProcessImage() {
    AnonLog();
    var control = document.getElementById("fileToUpload");
    var file = control.files[0];

    // Load base64 encoded image for display 
    var reader = new FileReader();
    reader.onload = (function (theFile) {
      return function (e) {
        //Call Rekognition  
        AWS.region = "RegionToUse";  
        var rekognition = new AWS.Rekognition();
        var params = {
          Image: {
          Bytes: e.target.result
        },
        Attributes: [
        'ALL',
      ]
    };
    rekognition.detectFaces(params, function (err, data) {
      if (err) console.log(err, err.stack); // an error occurred
      else {
       var table = "<table><tr><th>Low</th><th>High</th></tr>";
        // show each face and build out estimated age table
        for (var i = 0; i < data.FaceDetails.length; i++) {
          table += '<tr><td>' + data.FaceDetails[i].AgeRange.Low +
            '</td><td>' + data.FaceDetails[i].AgeRange.High + '</td></tr>';
        }
        table += "</table>";
        document.getElementById("opResult").innerHTML = table;
      }
    });

      };
    })(file);
    reader.readAsArrayBuffer(file);
  }
```

## 获取 Amazon Cognito 身份池标识符
<a name="image-bytes-javascript-auth"></a>

为简便起见，该示例使用一个匿名 Amazon Cognito 身份池来提供对 Amazon Rekognition Image API 的未经身份验证的访问。这可能适合您的需求。例如，您可以使用未经身份验证的访问来在用户登录前提供对网站的免费或试用访问。要提供经过身份验证的访问，请使用 Amazon Cognito 用户群体。有关更多信息，请参阅 [Amazon Cognito 用户群体](https://docs.aws.amazon.com/cognito/latest/developerguide/cognito-user-identity-pools.html)。

以下过程说明如何创建一个身份池来允许访问未经身份验证的身份，以及如何获取示例代码中所需的身份池标识符。

**获取身份池标识符**

1. 打开 [Amazon Cognito 控制台](https://console.aws.amazon.com/cognito/federated)。

1. 选择**创建新身份池**。

1. 对于**身份池名称\$1**，键入您的身份池的名称。

1. 在**未经验证的身份**中，选择**启用未经验证的身份的访问权限**。

1. 选择**创建池**。

1. 选择**查看详细信息**，并记下未经身份验证的身份的角色名称。

1. 选择**允许**。

1. 在**平台**中，选择**JavaScript**。

1. 在**获取 AWS 凭证**中，记下代码段中显示的 `AWS.config.region` 和 `IdentityPooldId` 的值。

1. 使用 [https://console.aws.amazon.com/iam/](https://console.aws.amazon.com/iam/) 打开 IAM 控制台。

1. 在导航窗格中，选择**角色**。

1. 选择您在步骤 6 中记下的角色名称。

1. 在**权限**选项卡中，选择**附加策略**。

1. 选择 **AmazonRekognitionReadOnlyAccess**。

1. 选择**附加策略**。