uniapp打开摄像头进行视频并拍照

引用

引用插件: 基于内置H5的人脸所识别组件.
引用文章:前端网页打开摄像头并将图像传给后端.

新建hybrid文件

提示:以下是本篇文章正文内容,下面案例可供参考

一、使用步骤

1.创建hybrid文件夹

在这里插入图片描述

代码如下(示例):

<!doctype html>
<html lang="en">
<head>
    <title>GET VIDEO</title>
    <meta charset="utf-8">
    <script type="text/javascript" src="//cdn.bootcss.com/jquery/3.1.1/jquery.min.js"></script>
</head>
<body>
	<div style="display: flex;align-items: center;justify-content: space-around;width: 100%;">
		<input type="button" title="开启摄像头" value="开启摄像头" onclick="getMedia()" style="padding: 30px;font-size: 80px;" />
		<button  style="padding: 30px;font-size: 80px;" id="snap" onclick="takePhoto()">拍照</button>
		<button  style="padding: 30px;font-size: 80px;" id="close" onclick="closeMedia()">关闭</button>
	</div>
	<div style="display: flex;align-items: center;justify-content: space-around;width: 100%;">
		<!-- autoplay 属性规定一旦视频就绪马上开始播放。如果设置了该属性,视频将自动播放。 -->
		<video id="video" width="500" height="500" autoplay="autoplay"></video>
		<canvas id="canvas" width="500" height="500"></canvas>		
	</div>
<script>
	var buffer;
    //获得video摄像头区域
	var video = document.getElementById('video');
	//获得Canvas对象
	let canvas = document.getElementById("canvas");
	let ctx = canvas.getContext('2d');
    function closeMedia() {
		try{
			buffer&&buffer.getTracks()[0].stop();//关闭摄像头
		}catch(e){
			//TODO handle the exception
			return;
		}
    }
    function getMedia() {
        let mediaConfig = {
			// 强制打开后置摄像头video:视频  audio:音频
			video: {facingMode: {exact: 'environment'}},
            audio: false,
			// 请求不带任何参数的视频和音频
			// vidio: true, audio: true
			// 指定视频分辨率
			// video: {width: 480, height: 320}
			// 移动设备,优先使用前置摄像头
			// video: {facingMode: 'user'}
			// 移动设备,优先使用后置摄像头
			// {video: {facingMode: {exact: 'environment'}}}
        };
		var errBack = function(e) {
			console.log('An error has occurred!', e)
		};
		if(navigator.mediaDevices && navigator.mediaDevices.getUserMedia) {
			navigator.mediaDevices.getUserMedia(mediaConfig).then(function(stream) {
				video.src = window.URL.createObjectURL(stream);
				// video.srcObject = stream;
				video.play();
				buffer = stream;
			});
		}else if(navigator.getUserMedia) { // Standard
			navigator.getUserMedia(mediaConfig, function(stream) {
				video.src = stream;
				video.play();
				buffer = stream;
			}, errBack);
		} else if(navigator.mozGetUserMedia) { // Mozilla-prefixed
			navigator.mozGetUserMedia(mediaConfig, function(stream){
				video.src = window.URL.createObjectURL(stream);
				video.play();
				buffer = stream;
			}, errBack);
		} else if(navigator.msGetUserMedia) { // Mozilla-prefixed
			navigator.msGetUserMedia(mediaConfig, function(stream){
				video.src = window.URL.createObjectURL(stream);
				video.play();
				buffer = stream;
			}, errBack);
		} else if(navigator.webkitGetUserMedia) { // WebKit-prefixed
			navigator.webkitGetUserMedia(mediaConfig, function(stream){
				video.src = window.URL.createObjectURL(stream);
				video.play();
				buffer = stream;
			}, errBack);
		}
    }
    function takePhoto() {
        ctx.drawImage(video, 0, 0, 500, 500);
		// 把画布的内容转换为base64编码格式的图片
		// var data = canvas.toDataURL( 'image/png',1);  //1表示质量(无损压缩)
		// return data.replace('data:image/png;base64,','');
    }
</script>
</body>
</html>

uniapp中page跳转的页面

代码如下(示例):

<template>
	<view>
		<web-view ref="webview" :src="url" @message="getMessage"></web-view>
	</view>
</template>
<script>
	export default {
		data(){
			return {
				//携带参数photo对象
				//url:'/hybrid/html/local.html#'+encodeURIComponent(JSON.stringify({
					//photo:uni.getStorageSync('photo')
				//}))
				//不携带参数直接切换到html页面
				url:'/hybrid/html/local.html#'  
			}
		},
		methods: {
		},
	}
</script>
<style>
</style>
UniApp中,使用摄像头进行人脸识别需要结合H5的getUserMedia API以及一些第三方库,如`ali-oss`用于图片上传,`facepp`或`qiniu`提供的人脸识别服务。这里是一个简单的示例,展示如何获取权限、打开摄像头并捕获人脸数据: ```html <template> <view> <button @click="openCamera">打开摄像头</button> </view> </template> <script> import facepp from '@faceplusplus/api'; export default { data() { return { cameraActive: false, imgSrc: '' }; }, methods: { async openCamera() { try { // 请求用户访问摄像头权限 const stream = await this.$camera.requestPermissions(); if (stream) { this.cameraActive = true; this.streaming(stream); } } catch (error) { console.error('Error accessing camera:', error); } }, streaming(stream) { const videoElement = document.createElement('video'); videoElement.srcObject = stream; // 开启预览 videoElement.play(); // 使用face++处理人脸识别 const faceppInstance = new facepp({ appid: 'your_faceplusplus_app_id', apikey: 'your_api_key', secretKey: 'your_secret_key' }); const faceppDetect = faceppInstance.detect({ sourceType: 'live', // 指定源类型为实时视频流 detectType: ['face'], // 只检测人脸 onResult: result => { if (result.length > 0) { // 对于每一个检测到的人脸,可以提取信息并做后续操作 const faceInfo = result; // 这里只是一个示例,实际应用可能会上传到云存储或执行其他逻辑 this.uploadFaceImage(faceInfo); } }, onError: error => { console.error('Error in face detection:', error); } }); // 监听视频元素的ended事件,当停止录制时关闭相机 videoElement.addEventListener('ended', () => { this.stopStreaming(); }); }, stopStreaming() { this.cameraActive = false; // 关闭资源释放 if (this.streaming && this.streaming.srcObject) { this.streaming.srcObject.getTracks().forEach(track => track.stop()); } }, uploadFaceImage(faceInfo) { // 将人脸图片转换为base64并上传到服务器,这里仅作示例,你需要替换为实际的上传代码 // ... 实际代码替换 ... } }, }; </script> ``` 注意:在实际项目中,你需要替换上述代码中的`your_faceplusplus_app_id`、`your_api_key`和`your_secret_key`为你的Face++ API密钥,并确保已安装了对应插件。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值