The merchant backend I recently built needed to implement the function of calling the camera to take photos of users checking in. I searched for information and researched it. Finally, Huang Tian paid off and succeeded. I will post the code step by step below, hoping it will be helpful.
The code is a bit much, but each step is easy to understand. The first is the HTML code. Write a form. When the time comes to upload the image, ajax will submit it asynchronously. There is no need to introduce other js. There is a method in h5 that can be directly adjusted. Get the media device.
However, it should be noted that for many browsers such as Google, QQ, 360, etc., due to security reasons, websites without HTTPS protocols are considered unsafe. Therefore, if you cannot retrieve them, you must remember to apply to the website. HTTPS certificate, installed on the server
During the testing period, their browser turned off the flash and camera equipment by default, and could not open it. I searched for various entrances, but there was no check-in button. Finally, I tried Try Firefox, Firefox can be retrieved, so it is recommended to use Firefox browser for development during the test phase
Requirements:
The photo and the photo must be taken in the same position, after taking the photo In the future, the video box will display the photo. If you want to retake, click the Activate Camera button. The video box will be displayed and the photo will be hidden. Then click Shoot. If the shooting is successful, click Upload.
The camera is successfully called, as shown in the video box with a progress bar as shown below:
Click to take a photo, the shooting is successful, and the activation of the camera will be displayed on the left Button, actually don’t click to activate the camera. If you are not satisfied and click to take a picture, you can take a picture, but you can’t see what it looks like, as shown in the picture:
The shooting is completed. Click Upload to upload to the background for data operations.
Style file:
.coach-price{display: none} .input-but{display: inline-flex;} #canvas{display: none} #showVideo{display: none} #input-picture{width:100%;} HTML代码: <div class="ibox float-e-margins"> <div class="ibox-title"> <h5>打卡头像</h5> </div> <div class="ibox-content img-content"> <form class="form-horizontal m-t" id="upPictureForm" method="post" action=""> <div class="form-group " id="input-picture"> <div class="img-box" id="results"> <input name="image_code" id="image_code" type="hidden" value=""/> <input name="userId" class="userId" type="hidden" value=""/> //这是一个画布的容器 <canvas id="canvas" width="300" height="260"></canvas> </div> </div> <div class="form-group "> //要拍照的视频框 <video id="video" controls> </video> </div> <div class="form-group "> //各种按钮 <div class="input-but"> <button type="button" class="layui-btn" id="showVideo"> 激活摄像头 </button> <button type="button" class="layui-btn" id="capture"> <i class="layui-icon"></i>拍照 </button> <button type="button" id="uppicture" class="layui-btn" > <i class="layui-icon"></i>上传 </button> </div> </div> </form> </div> </div>
JS code:
<script> //访问用户媒体设备的兼容方法 function getUserMedia(constraints, success, error) { if (navigator.mediaDevices.getUserMedia) { //最新的标准API navigator.mediaDevices.getUserMedia(constraints).then(success).catch(error); } else if (navigator.webkitGetUserMedia) { //webkit核心浏览器 navigator.webkitGetUserMedia(constraints,success, error) } else if (navigator.mozGetUserMedia) { //firfox浏览器 navigator.mozGetUserMedia(constraints, success, error); } else if (navigator.getUserMedia) { //旧版API navigator.getUserMedia(constraints, success, error); } } function success(stream) { //兼容webkit核心浏览器 let CompatibleURL = window.URL || window.webkitURL; //将视频流设置为video元素的源 console.log(stream); //video.src = CompatibleURL.createObjectURL(stream); video.srcObject = stream; video.play(); } function error(error) { alert(`访问用户摄像头失败${error.name}, ${error.message}`); } //从 canvas 提取图片 image function convertCanvasToImage(canvas) { //新Image对象,可以理解为DOM var image = new Image(); // canvas.toDataURL 返回的是一串Base64编码的URL // 指定格式 PNG image.src = canvas.toDataURL("image/png"); return image; } function getnavigator() { if (navigator.mediaDevices.getUserMedia || navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia) { //获取video宽高 var v_height,v_width; var myvObj = document.getElementById("video"); myvObj.addEventListener("loadedmetadata", function () { v_height = this.videoHeight; v_width =this.videoWidth; $('#canvas').attr('width',v_width); $('#canvas').attr('height',v_height); }); //调用用户媒体设备, 访问摄像头 getUserMedia({video : {width: 320, height: 240}}, success, error); } else { alert('不支持访问用户媒体'); } } getnavigator(); function showVideo(){ $('#results').find('img').remove(); $('#canvas').css('display','none'); $('#video').css('display','block'); $('#showVideo').css('display','none'); getnavigator(); } function showpicture(picture) { if($('#results').find('img').attr('src')){ $('#results').find('img').attr('src',picture); }else{ $('#results').append('<img src="'+picture+'"/ alt="How to use php to call the camera to implement the camera function" >'); } $('#video').css('display','none'); $('#canvas').css('display','none'); $('#showVideo').show(); $('.picture').val(1); } function hidepicture() { $('#results').find('img').remove(); getnavigator(); $('#video').css('display','block'); $('#canvas').css('display','none'); $('#showVideo').css('display','none'); } $('#showVideo').click(function () { showVideo(); }); document.getElementById('capture').addEventListener('click', function () { let video = document.getElementById('video'); let canvas = document.getElementById('canvas'); let context = canvas.getContext('2d'); context.drawImage(video, 0, 0); //获取网页中的canvas对象 var mycans=$('canvas')[0]; //调用convertCanvasToImage函数将canvas转化为img形式 var img=convertCanvasToImage(mycans); if(img.src){ $('#results').find('#image_code').val(img.src); // $('#capture').text('修改'); $('#video').css('display','none'); $('#canvas').css('display','block'); $('#showVideo').show(); } }) //点击图片上传按钮 $('#uppicture').click(function () { var userId = $('.userId').val(); var image_code = $('#image_code').val();//图片值 if(!userId){ alert('用户不存在');return; } if(!image_code){ alert('请先拍照');return; } $.post("{:url('upPicture')}", {'userId':userId,'image_code':image_code}, function(res){ // console.log(res); if(1 == res.code){ layer.alert(res.msg, {title: '友情提示', icon: 1}); $('.picture').val(1); }else{ layer.alert(res.msg, {title: '友情提示', icon: 2}); } }); }); </script>
Submit to the background, PHP processes it, and the framework used is tp5 , so it is very convenient to directly use the success and error of tp when returning later. Its first parameter is msg, the second is the URL, and the third is data.
public function upPicture(){ $image_code = input('image_code'); if(empty($image_code)){ $this ->error('照片为空'); } $uId = input('userId'); //处理接收过来的图片 $img = str_replace('data:image/png;base64,', '', $image_code); $img = str_replace(' ', '+', $img); $data = base64_decode($img); // 图片名称 $file_name = "./uploads/head/".time().".png"; $fp = fopen($file_name, 'w'); fwrite($fp, $data); fclose($fp); $array = array( "picture" => substr($file_name,1) ); $res = Db::table("table")->where("userId",$uId)->setField($array); if($res){ $this ->success('编辑成功!'); }else{ $this ->error('编辑失败,请刷新重试!'); } }
Related recommendations: "PHP Tutorial"
The above is the detailed content of How to use php to call the camera to implement the camera function. For more information, please follow other related articles on the PHP Chinese website!