一路繁花似锦绣前程
失败的越多,成功才越有价值

导航

 
<!DOCTYPE html>
<html>
<head>
  <title>js调用摄像头并截图转file对象</title>
  <meta charset="utf-8"/>
</head>
<body>
<video id="video" width="300" height="300"></video>
<canvas id="canvas" width="300" height="300"></canvas>
<p>
  <button onclick="startFun()">打开摄像头</button>
  <button onclick="snapFun()">截取图像</button>
  <button onclick="closeFun()">关闭摄像头</button>
</p>
<script>
  var videoObj = document.getElementById('video')
  var canvasObj = document.getElementById('canvas')
  var MediaStreamTrackArr = null

  function startFun() {
    navigator.mediaDevices.getUserMedia({
      video: true,//视频
      audio: true//音频
    }).then(function (stream) {
      MediaStreamTrackArr = stream.getTracks();
      videoObj.srcObject = stream
      videoObj.play();
    })
  }

  function snapFun() {
    var context2d = canvasObj.getContext('2d')
    context2d.drawImage(videoObj, 0, 0, 300, 300);

    // canvas转base64
    const base64Data = canvasObj.toDataURL('image/png');
    // 方式1
    // base64转blob
    const blob = base64ToBlob(base64Data);
    // blob转file
    const file1 = blobToFile(blob, '文件名');

    // 方式2
    // base64转file
    const file2 = base64ToFile(base64Data, '文件名');
    console.log(file2)
  }

  function closeFun() {
    for (var i = 0; i < MediaStreamTrackArr.length; i++) {
      MediaStreamTrackArr[i].stop()
    }
  }

  function base64ToBlob(base64Data) {
    let arr = base64Data.split(','),
      fileType = arr[0].match(/:(.*?);/)[1],
      bstr = atob(arr[1]),
      l = bstr.length,
      u8Arr = new Uint8Array(l);

    while (l--) {
      u8Arr[l] = bstr.charCodeAt(l);
    }
    return new Blob([u8Arr], {type: fileType});
  }

  function blobToFile(newBlob, fileName) {
    newBlob.lastModifiedDate = new Date();
    newBlob.name = fileName;
    return newBlob;
  }

  function base64ToFile(base64Data, fileName) {
    let arr = base64Data.split(','),
      fileType = arr[0].match(/:(.*?);/)[1],
      bstr = atob(arr[1]),
      l = bstr.length,
      u8Arr = new Uint8Array(l);

    while (l--) {
      u8Arr[l] = bstr.charCodeAt(l);
    }
    return new File([u8Arr], fileName, {type: fileType});
  }
</script>
</body>
</html>

 

posted on 2021-04-08 21:28  一路繁花似锦绣前程  阅读(230)  评论(0编辑  收藏  举报