H5调用摄像头拍照并下载照片

14 篇文章 0 订阅

类似需求基本粘贴复制就能用

调用摄像头拍照转成base64格式后下载图片,这个没什么花里胡哨的骚操作,直接看代码 (canvas + video)

<html >
<style>
  body{
    text-align: center;
  }
  button{
    width: 100px;
    height: 40px;
    background-color: #d35555;
    border-radius: 5px;
    border:none;
    color: azure;
    margin: 0px 5px;
  }
  .center{
    text-align: center;
    width: 500px;
    margin: 20px auto;
  }
  .bg{
    margin: 0 auto;
    width: 460px;
  }
  #qr-canvas{
    margin: 10px auto;
    width: 460px;
  }
</style>

<!-- 功能按钮 -->
<p class="center">
 <button onclick="openMedia()">打开摄像头</button>
 <button onclick="closeMedia()">关闭摄像头</button>
 <button onclick="drawMedia()">截取照片</button>
 <button onclick="loadimg()">下载照片</button>
</p>
<!-- 摄像头画面 -->
<video id="video" class="bg"></video>
<br>
<!-- 截图画面 -->
<canvas id="qr-canvas"></canvas>

<img id="imgload">

<script type="text/javascript">
    var video = document.querySelector('video');
    var text = document.getElementById('text');
    var imgload = document.getElementById('imgload');
    var canvas1 = document.getElementById('qr-canvas');
    var context1 = canvas1.getContext('2d');
    var mediaStreamTrack;
    var state = false

    // 一堆兼容代码
    window.URL = (window.URL || window.webkitURL || window.mozURL || window.msURL);
    if (navigator.mediaDevices === undefined) {
        navigator.mediaDevices = {};
    }
    if (navigator.mediaDevices.getUserMedia === undefined) {
        navigator.mediaDevices.getUserMedia = function(constraints) {
            var getUserMedia = navigator.webkitGetUserMedia || navigator.mozGetUserMedia || navigator.msGetUserMedia;
            if (!getUserMedia) {
                return Promise.reject(new Error('getUserMedia is not implemented in this browser'));
            }
            return new Promise(function(resolve, reject) {
                getUserMedia.call(navigator, constraints, resolve, reject);
            });
        }
    } 
 
     //摄像头调用配置
     var mediaOpts = {
         audio: false,
         video: true,
         video: { facingMode: "environment"} // 或者 "user"
         // video: { width: 1280, height: 720 }
         // video: { facingMode: { exact: "environment" } }// 或者 "user"
     }
 
     // 回调
     function successFunc(stream) {
         mediaStreamTrack = stream;
         video = document.querySelector('video');
         if ("srcObject" in video) {
            video.srcObject = stream
         } else {
            video.src = window.URL && window.URL.createObjectURL(stream) || stream
         }
         video.play();
     }
     function errorFunc(err) {
        alert(err.name);
     }
     
     // 正式启动摄像头
     function openMedia(){
        navigator.mediaDevices.getUserMedia(mediaOpts).then(successFunc).catch(errorFunc);
     }
 
     //关闭摄像头
     function closeMedia(){
         mediaStreamTrack.getVideoTracks().forEach(function (track) {
          track.stop();
          context1.clearRect(0, 0,context1.width, context1.height);//清除画布
         });
     }
 
     //截取视频
     function drawMedia(){
         canvas1.setAttribute("width", video.videoWidth);
         canvas1.setAttribute("height", video.videoHeight);
         context1.drawImage(video, 0, 0, video.videoWidth, video.videoHeight);
         state=true
     }
     //下载
     function loadimg(){
       
      if(state){
        // 转base64格式、图片格式转换、图片质量压缩
        let imgBase64 =  document.getElementById('qr-canvas').toDataURL('image/jpeg', 0.7)
        
        // // 由字节转换为KB 判断大小
        //   let str = imgBase64.replace('data:image/jpeg;base64,', '')
        //   let strLength = str.length
        //   let fileLength = parseInt(strLength - (strLength / 8) * 2)
        // 图片尺寸  用于判断
        // let size = (fileLength / 1024).toFixed(2)

        // console.log(imgBase64)
        //base64转blob
        let parts = imgBase64.split(';base64,');
        let contentType = parts[0].split(':')[1];
        let raw = window.atob(parts[1]);
        let rawLength = raw.length;
        let uInt8Array = new Uint8Array(rawLength);
        for (let i = 0; i < rawLength; ++i) {
          uInt8Array[i] = raw.charCodeAt(i);
        }
        let Blobimg=new Blob([uInt8Array], {type: contentType});

        let aLink = document.createElement('a');
        let evt = document.createEvent("HTMLEvents");
        evt.initEvent("click", true, true);//initEvent 不加后两个参数在FF下会报错  事件类型,是否冒泡,是否阻止浏览器的默认行为
        aLink.download = '下载照片.png';//自定义文件名
        aLink.href = URL.createObjectURL(Blobimg);
        // aLink.dispatchEvent(evt);
        aLink.click()

      }else{
        alert('请截取照片')
      }
        
     }
 
</script>
</html>

效果

评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

学而时习之不亦说乎。

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值