


How to use php to call the camera to implement the camera function
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/imghw/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!

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

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

PHP 8.4 brings several new features, security improvements, and performance improvements with healthy amounts of feature deprecations and removals. This guide explains how to install PHP 8.4 or upgrade to PHP 8.4 on Ubuntu, Debian, or their derivati

If you are an experienced PHP developer, you might have the feeling that you’ve been there and done that already.You have developed a significant number of applications, debugged millions of lines of code, and tweaked a bunch of scripts to achieve op

Visual Studio Code, also known as VS Code, is a free source code editor — or integrated development environment (IDE) — available for all major operating systems. With a large collection of extensions for many programming languages, VS Code can be c

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

A string is a sequence of characters, including letters, numbers, and symbols. This tutorial will learn how to calculate the number of vowels in a given string in PHP using different methods. The vowels in English are a, e, i, o, u, and they can be uppercase or lowercase. What is a vowel? Vowels are alphabetic characters that represent a specific pronunciation. There are five vowels in English, including uppercase and lowercase: a, e, i, o, u Example 1 Input: String = "Tutorialspoint" Output: 6 explain The vowels in the string "Tutorialspoint" are u, o, i, a, o, i. There are 6 yuan in total

This tutorial demonstrates how to efficiently process XML documents using PHP. XML (eXtensible Markup Language) is a versatile text-based markup language designed for both human readability and machine parsing. It's commonly used for data storage an

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

What are the magic methods of PHP? PHP's magic methods include: 1.\_\_construct, used to initialize objects; 2.\_\_destruct, used to clean up resources; 3.\_\_call, handle non-existent method calls; 4.\_\_get, implement dynamic attribute access; 5.\_\_set, implement dynamic attribute settings. These methods are automatically called in certain situations, improving code flexibility and efficiency.
