使用设备摄像头在 reactjs 中捕获图像

Posted

技术标签:

【中文标题】使用设备摄像头在 reactjs 中捕获图像【英文标题】:using device camera for capturing image in reactjs 【发布时间】:2021-01-28 04:34:51 【问题描述】:

我可以访问设备相机并在 ReactJs 中拍照吗?目标是创建一个组件,允许相机通过单击按钮来拍照。根据我的研究,我应该使用 mediaDevices,但我正在寻找 ReactJs 中的示例代码。请向我提供示例代码,或者如果您有实现此代码的经验,请指导我。

【问题讨论】:

【参考方案1】:

我已经准备了一个可以用作组件的示例代码。此代码 sn-p 适用于也有两个摄像头的设备。如果您想拍摄视频而不是照片,您还可以在输出中启用音频功能。

import React from "react";

class App extends React.Component 
  constructor() 
    super();

    this.cameraNumber = 0;

    this.state = 
      imageDataURL: null,
    ;
  

  initializeMedia = async () => 
    this.setState( imageDataURL: null );

    if (!("mediaDevices" in navigator)) 
      navigator.mediaDevices = ;
    

    if (!("getUserMedia" in navigator.mediaDevices)) 
      navigator.mediaDevices.getUserMedia = function (constraints) 
        var getUserMedia =
          navigator.webkitGetUserMedia || navigator.mozGetUserMedia;

        if (!getUserMedia) 
          return Promise.reject(new Error("getUserMedia Not Implemented"));
        

        return new Promise((resolve, reject) => 
          getUserMedia.call(navigator, constraints, resolve, reject);
        );
      ;
    

    //Get the details of video inputs of the device
    const videoInputs = await this.getListOfVideoInputs();

    //The device has a camera
    if (videoInputs.length) 
      navigator.mediaDevices
        .getUserMedia(
          video: 
            deviceId: 
              exact: videoInputs[this.cameraNumber].deviceId,
            ,
          ,
        )
        .then((stream) => 
          this.player.srcObject = stream;
        )
        .catch((error) => 
          console.error(error);
        );
     else 
      alert("The device does not have a camera");
    
  ;

  capturePicture = () => 
    var canvas = document.createElement("canvas");
    canvas.width = this.player.videoWidth;
    canvas.height = this.player.videoHeight;
    var contex = canvas.getContext("2d");
    contex.drawImage(this.player, 0, 0, canvas.width, canvas.height);
    this.player.srcObject.getVideoTracks().forEach((track) => 
      track.stop();
    );

    console.log(canvas.toDataURL());
    this.setState( imageDataURL: canvas.toDataURL() );
  ;

  switchCamera = async () => 
    const listOfVideoInputs = await this.getListOfVideoInputs();

    // The device has more than one camera
    if (listOfVideoInputs.length > 1) 
      if (this.player.srcObject) 
        this.player.srcObject.getVideoTracks().forEach((track) => 
          track.stop();
        );
      

      // switch to second camera
      if (this.cameraNumber === 0) 
        this.cameraNumber = 1;
      
      // switch to first camera
      else if (this.cameraNumber === 1) 
        this.cameraNumber = 0;
      

      // Restart based on camera input
      this.initializeMedia();
     else if (listOfVideoInputs.length === 1) 
      alert("The device has only one camera");
     else 
      alert("The device does not have a camera");
    
  ;

  getListOfVideoInputs = async () => 
    // Get the details of audio and video output of the device
    const enumerateDevices = await navigator.mediaDevices.enumerateDevices();

    //Filter video outputs (for devices with multiple cameras)
    return enumerateDevices.filter((device) => device.kind === "videoinput");
  ;

  render() 
    const playerORImage = Boolean(this.state.imageDataURL) ? (
      <img src=this.state.imageDataURL  />
    ) : (
      <video
        ref=(refrence) => 
          this.player = refrence;
        
        autoPlay
      ></video>
    );

    return (
      <div className="App">
        playerORImage
        <button onClick=this.initializeMedia>Take Photo</button>
        <button onClick=this.capturePicture>Capture</button>
        <button onClick=this.switchCamera>Switch</button>
      </div>
    );
  


export default App;

【讨论】:

近 3 个小时以来,我一直在寻找如何在 React 应用程序中拍照而不使用 3rd 包。我遇到了你的答案,我真的很感激。人们大多打算对几乎所有东西都使用 3rd 方包,很难找到一个答案,即如何只使用语言本身来制作任何东西。再次感谢。

以上是关于使用设备摄像头在 reactjs 中捕获图像的主要内容,如果未能解决你的问题,请参考以下文章

在 android 设备中使用相机显示图像捕获

在设备被密码锁定时捕获图像

在 PhoneGap 中读取图像捕获文件

Python-视频

如何挂钩网络摄像头捕获?

使用 Blazor 访问设备摄像头