Posting An Image from Webcam to Azure Face Api

前端 未结 4 1927
广开言路
广开言路 2021-01-06 19:12

I am trying to upload an image that I get from my webcam to the Microsoft Azure Face Api. I get the image from canvas.toDataUrl(‘image/png’) which contains the Data Uri. I c

4条回答
  •  失恋的感觉
    2021-01-06 19:46

    For saving someone's 6 hours, I appended my right code. I hope this code helps you.

    Tools

    • React
    • Typescript
    • React-webcam
    • Mac OS
    • Axios

    Code

    index.tsx

    Constants and ref

    /**
     * Constants
     */
    const videoConstraints = {
      width: 1280,
      height: 720,
      facingMode: 'user',
    };
    /**
     * Refs
     */
    const webcamRef = React.useRef(null);
    

    Call back function

    const capture = React.useCallback(() => {
      const base64Str = webcamRef.current!.getScreenshot() || '';
      const s = base64Str.split(',');
      const blob = b64toBlob(s[1]);
      callCognitiveApi(blob);
    }, [webcamRef]);
    

    In render

    
    
    

    base64toBlob

    Thanks to creating-a-blob-from-a-base64-string-in-javascript

    export const b64toBlob = (b64DataStr: string, contentType = '', sliceSize = 512) => {
      const byteCharacters = atob(b64DataStr);
      const byteArrays = [];
    
      for (let offset = 0; offset < byteCharacters.length; offset += sliceSize) {
        const slice = byteCharacters.slice(offset, offset + sliceSize);
    
        const byteNumbers = new Array(slice.length);
        for (let i = 0; i < slice.length; i++) {
          byteNumbers[i] = slice.charCodeAt(i);
        }
    
        const byteArray = new Uint8Array(byteNumbers);
        byteArrays.push(byteArray);
      }
    
      const blob = new Blob(byteArrays, { type: contentType });
      return blob;
    };
    

    callCognitiveApi

    import axios from 'axios';
    
    const subscriptionKey: string = 'This_is_your_subscription_key';
    const url: string = 'https://this-is-your-site.cognitiveservices.azure.com/face/v1.0/detect';
    export const callCognitiveApi = (data: any) => {
      const config = {
        headers: { 'content-type': 'application/octet-stream', 'Ocp-Apim-Subscription-Key': subscriptionKey },
      };
      const response = axios
        .post(url, data, config)
        .then((res) => {
          console.log(res);
        })
        .catch((error) => {
          console.error(error);
        });
    };
    

    Result

提交回复
热议问题