public async getBoundingBox()

in source/image-handler/image-handler.ts [338:377]


  public async getBoundingBox(imageBuffer: Buffer, faceIndex: number): Promise<BoundingBox> {
    const params = { Image: { Bytes: imageBuffer } };

    try {
      const response = await this.rekognitionClient.detectFaces(params).promise();
      if (response.FaceDetails.length <= 0) {
        return { height: 1, left: 0, top: 0, width: 1 };
      }

      const boundingBox: { Height?: number; Left?: number; Top?: number; Width?: number } = {};
      // handle bounds > 1 and < 0
      for (const bound in response.FaceDetails[faceIndex].BoundingBox) {
        if (response.FaceDetails[faceIndex].BoundingBox[bound] < 0) boundingBox[bound] = 0;
        else if (response.FaceDetails[faceIndex].BoundingBox[bound] > 1) boundingBox[bound] = 1;
        else boundingBox[bound] = response.FaceDetails[faceIndex].BoundingBox[bound];
      }

      // handle bounds greater than the size of the image
      if (boundingBox.Left + boundingBox.Width > 1) {
        boundingBox.Width = 1 - boundingBox.Left;
      }
      if (boundingBox.Top + boundingBox.Height > 1) {
        boundingBox.Height = 1 - boundingBox.Top;
      }

      return { height: boundingBox.Height, left: boundingBox.Left, top: boundingBox.Top, width: boundingBox.Width };
    } catch (error) {
      console.error(error);

      if (error.message === "Cannot read property 'BoundingBox' of undefined" || error.message === "Cannot read properties of undefined (reading 'BoundingBox')") {
        throw new ImageHandlerError(
          StatusCodes.BAD_REQUEST,
          'SmartCrop::FaceIndexOutOfRange',
          'You have provided a FaceIndex value that exceeds the length of the zero-based detectedFaces array. Please specify a value that is in-range.'
        );
      } else {
        throw new ImageHandlerError(error.statusCode ? error.statusCode : StatusCodes.INTERNAL_SERVER_ERROR, error.code, error.message);
      }
    }
  }