uniapp调用摄像头然后用canvas进行截屏并上传服务器

<template>
    <div>
        <div class="viewfinder">
            <div class="wrap-box" ref="wrap">
            </div>
        </div>
    </div>
</template>
<script>
    let canvasEle = null
    let video = null
    import {
        UpImgHttp
    } from '../../utils/https.js'
    import {
        warn
    } from "vue"
    export default {
        components: {},
        data() {
            return {
                ioswx: '',
                imageFile: "",
                timerIntv: null, //只需要此参数
            }
        },
        onLoad() {},
        mounted() {
            // uniapp必须创建元素不然获取不到里面的方法
            video = document.createElement('video')
            video.setAttribute('position', 'fixed')
            video.setAttribute('height', '100%')
            video.setAttribute('autoplay', true)
            video.setAttribute('width', '100%')
            canvasEle = document.createElement('canvas')
            canvasEle.width = 450
            canvasEle.height = 450
            var wrap = this.$refs.wrap
            // wrap.appendChild(canvasEle)
            console.log(wrap);
            wrap.appendChild(video)
            this.ioswx = this.isWXandIos();
            // this.openCamera();
        },
        onShow() {
            this.openCamera();
            this.takePhoto()
        },
        methods: {
            isWXandIos() {
                const aegent = navigator.userAgent.toLowerCase();
                if (/micromessenger/.test(aegent) && /iPhone|mac|iPod|iPad/i.test(aegent)) {
                    return true;
                }
                return false;
            },
            async openCamera() {
                const constraints = {
                    audio: false,
                    video: {
                        facingMode: 'environment',
                        width: {
                            min: 1280,
                            ideal: 2040
                        },
                        height: {
                            min: 720,
                            ideal: 1080
                        },
                    },
                };
                // 兼容
                // 老的浏览器没实现mediaDevices
                if (navigator.mediaDevices === undefined) navigator.mediaDevices = {};
                if (navigator.mediaDevices.getUserMedia === undefined) {
                    navigator.mediaDevices.getUserMedia = function(constraints) {
                        const getUserMedia = navigator.getUserMedia || navigator.webkitGetUserMedia ||
                            navigator
                            .mozGetUserMedia || navigator.msGetUserMedia || navigator.oGetUserMedia;
                        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);
                        });
                    };
                }
                // 获取视频流
                const that = this;
                navigator.mediaDevices.getUserMedia(constraints)
                    .then(function(stream) {
                        const video = document.querySelector('video');
                        video.srcObject = stream;
                        video.onloadedmetadata = function() {
                            video.play();
                        };
                        // 不是微信内置浏览器
                        if (!that.ioswx) {
                            that.status = 1;
                        }
                    })
                    .catch(function(err) {
                        // 调用原始摄像头;
                        that.originCamera();
                    });
            },
            originCamera() {
                // const that = this;
                const promise = new Promise(function(resolve, reject) {
                    const file = document.getElementById('file');
                    file.click();
                    file.onchange = function(event) {
                        if (!event) {
                            reject('empty');
                        }
                        const file = event.target.files[0];
                        resolve(file);
                    };
                });
                promise.then(value => {});
            },
            takePhoto() {
                this.timerIntv = setInterval(() => {
                    // 待处理业务逻辑    
                    var aspectRatio = video.videoWidth / video.videoHeight;
                    canvasEle.getContext('2d').drawImage(video, 0, 0, canvasEle.width, canvasEle.width /
                        aspectRatio);
                    this.imageFile = this.canvasToFile(canvasEle);
                    // const p = new Promise(resolve => {
                    //     // 将截图转化为blob文件
                    //     canvasEle.toBlob(blob => {
                    //         const url = URL.createObjectURL(blob);
                    //         resolve(url);
                    //     });
                    // });
                    // const that = this;
                    // p.then(value => {
                    //     that.imageUrl = value;
                    // });
                }, 5000)
            },
            // 将截图转化为base64格式,通过','分割,将后面的base64值转化为文件格式
            canvasToFile(canvas) {
                const dataurl = canvas.toDataURL('image/png');
                var data = {
                    url: dataurl.split(',')[1]
                }
                UpImgHttp(data).then(res => {
                    alert(res.msg)
                    if (JSON.parse(res.msg).error_msg == 'SUCCESS') {
                        uni.navigateTo({
                            url: `../photograph/photograph?Stu_id=${JSON.parse(res.msg).result.user_list[0].user_id}`
                        })
                    } else {
                        uni.showToast({
                            icon: "error",
                            title: "暂无信息",
                            duration: 1000
                        })
                    }
                }).catch(res => {
                    alert(res)
                })
                // 以下是通过','分割,将后面的base64值转化为文件格式
                // let arr = dataurl.split(','),
                //     mime = arr[0].match(/:(.*?);/)[1],
                //     bstr = atob(arr[1]),
                //     n = bstr.length,
                //     u8arr = new Uint8Array(n);
                // while (n--) {
                //     u8arr[n] = bstr.charCodeAt(n);
                // }
                // const file = new File([u8arr], 'phone.png', {
                //     type: mime
                // });
                // return file;
            },
        },
        onHide() {
            clearInterval(this.timerIntv)
        },
        destroyed() {
            clearInterval(this.timerIntv)
        }
    }
</script>
<style lang="scss" scoped>
    .wrap-box {
        width: 100%;
        height: 100%;
        position: relative;
    }
</style>

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
你可以使用uniapp的live-pusher组件调用前置摄像头,并结合人脸识别库来实现人脸识别功能。下面是一个简单的示例代码: 1. 首先,在页面中引入live-pusher组件和人脸识别库: ``` <template> <view> <live-pusher id="livePusher" url="rtmp://xxx.xxx.xxx.xxx/live/xxx" mode="RTC" camera="front"></live-pusher> <canvas id="canvas"></canvas> </view> </template> <script> import * as faceapi from 'face-api.js'; export default { mounted() { this.initFaceRecognition(); }, methods: { async initFaceRecognition() { await faceapi.nets.ssdMobilenetv1.loadFromUri('/models'); await faceapi.nets.faceLandmark68Net.loadFromUri('/models'); await faceapi.nets.faceRecognitionNet.loadFromUri('/models'); } } } </script> <style> #canvas { position: absolute; top: 0; left: 0; } </style> ``` 2. 在页面加载完成后,初始化人脸识别库。 3. 在需要进行人脸识别的地方,使用canvas绘制视频流中的图像,并进行人脸识别: ``` const video = document.getElementById('livePusher'); const canvas = document.getElementById('canvas'); const displaySize = { width: video.width, height: video.height }; faceapi.matchDimensions(canvas, displaySize); setInterval(async () => { const detections = await faceapi.detectAllFaces(video).withFaceLandmarks().withFaceDescriptors(); const resizedDetections = faceapi.resizeResults(detections, displaySize); canvas.getContext('2d').clearRect(0, 0, canvas.width, canvas.height); faceapi.draw.drawDetections(canvas, resizedDetections); faceapi.draw.drawFaceLandmarks(canvas, resizedDetections); faceapi.draw.drawFaceExpressions(canvas, resizedDetections); }, 100); ``` 这样,你就可以调用前置摄像头,在画面中进行人脸识别并绘制人脸边框、关键点和表情了。注意,你需要将人脸识别库的模型文件放置在项目的/models目录下。 希望对你有帮助!如有其他问题,请随时提问。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值