


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 id="打卡头像">打卡头像</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="/static/imghwm/default1.png" data-src="'+picture+'" class="lazy" / 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!

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

PHP remains important in the modernization process because it supports a large number of websites and applications and adapts to development needs through frameworks. 1.PHP7 improves performance and introduces new features. 2. Modern frameworks such as Laravel, Symfony and CodeIgniter simplify development and improve code quality. 3. Performance optimization and best practices further improve application efficiency.

PHPhassignificantlyimpactedwebdevelopmentandextendsbeyondit.1)ItpowersmajorplatformslikeWordPressandexcelsindatabaseinteractions.2)PHP'sadaptabilityallowsittoscaleforlargeapplicationsusingframeworkslikeLaravel.3)Beyondweb,PHPisusedincommand-linescrip

PHP type prompts to improve code quality and readability. 1) Scalar type tips: Since PHP7.0, basic data types are allowed to be specified in function parameters, such as int, float, etc. 2) Return type prompt: Ensure the consistency of the function return value type. 3) Union type prompt: Since PHP8.0, multiple types are allowed to be specified in function parameters or return values. 4) Nullable type prompt: Allows to include null values and handle functions that may return null values.

In PHP, use the clone keyword to create a copy of the object and customize the cloning behavior through the \_\_clone magic method. 1. Use the clone keyword to make a shallow copy, cloning the object's properties but not the object's properties. 2. The \_\_clone method can deeply copy nested objects to avoid shallow copying problems. 3. Pay attention to avoid circular references and performance problems in cloning, and optimize cloning operations to improve efficiency.

PHP is suitable for web development and content management systems, and Python is suitable for data science, machine learning and automation scripts. 1.PHP performs well in building fast and scalable websites and applications and is commonly used in CMS such as WordPress. 2. Python has performed outstandingly in the fields of data science and machine learning, with rich libraries such as NumPy and TensorFlow.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Dreamweaver Mac version
Visual web development tools

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

WebStorm Mac version
Useful JavaScript development tools