Home > Backend Development > PHP Tutorial > How to use php to call the camera to implement the camera function

How to use php to call the camera to implement the camera function

藏色散人
Release: 2023-04-07 22:14:01
forward
5700 people have browsed it

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:

How to use php to call the camera to implement the camera function

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:

How to use php to call the camera to implement the camera function

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">&#xe67c;</i>拍照
                    </button>
                    <button type="button" id="uppicture" class="layui-btn" >
                        <i class="layui-icon">&#xe67c;</i>上传
                    </button>
                </div>
            </div>
        </form>
    </div>
</div>
Copy after login

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;
                $(&#39;#canvas&#39;).attr(&#39;width&#39;,v_width);
                $(&#39;#canvas&#39;).attr(&#39;height&#39;,v_height);
            });
            //调用用户媒体设备, 访问摄像头
            getUserMedia({video : {width: 320, height: 240}}, success, error);
        } else {
            alert(&#39;不支持访问用户媒体&#39;);
        }
    }
    getnavigator();
    function showVideo(){
        $(&#39;#results&#39;).find(&#39;img&#39;).remove();
        $(&#39;#canvas&#39;).css(&#39;display&#39;,&#39;none&#39;);
        $(&#39;#video&#39;).css(&#39;display&#39;,&#39;block&#39;);
        $(&#39;#showVideo&#39;).css(&#39;display&#39;,&#39;none&#39;);
        getnavigator();
    }
    function showpicture(picture) {
        if($(&#39;#results&#39;).find(&#39;img&#39;).attr(&#39;src&#39;)){
            $(&#39;#results&#39;).find(&#39;img&#39;).attr(&#39;src&#39;,picture);
        }else{
            $(&#39;#results&#39;).append(&#39;<img  src="&#39;+picture+&#39;"/ alt="How to use php to call the camera to implement the camera function" >&#39;);
        }
        $(&#39;#video&#39;).css(&#39;display&#39;,&#39;none&#39;);
        $(&#39;#canvas&#39;).css(&#39;display&#39;,&#39;none&#39;);
        $(&#39;#showVideo&#39;).show();
        $(&#39;.picture&#39;).val(1);
    }
    function hidepicture() {
        $(&#39;#results&#39;).find(&#39;img&#39;).remove();
        getnavigator();
        $(&#39;#video&#39;).css(&#39;display&#39;,&#39;block&#39;);
        $(&#39;#canvas&#39;).css(&#39;display&#39;,&#39;none&#39;);
        $(&#39;#showVideo&#39;).css(&#39;display&#39;,&#39;none&#39;);
    }
    $(&#39;#showVideo&#39;).click(function () {
        showVideo();
    });
    document.getElementById(&#39;capture&#39;).addEventListener(&#39;click&#39;, function () {
        let video = document.getElementById(&#39;video&#39;);
        let canvas = document.getElementById(&#39;canvas&#39;);
        let context = canvas.getContext(&#39;2d&#39;);
        context.drawImage(video, 0, 0);
        //获取网页中的canvas对象
        var mycans=$(&#39;canvas&#39;)[0];
        //调用convertCanvasToImage函数将canvas转化为img形式
        var img=convertCanvasToImage(mycans);
        if(img.src){
            $(&#39;#results&#39;).find(&#39;#image_code&#39;).val(img.src);
            // $(&#39;#capture&#39;).text(&#39;修改&#39;);
            $(&#39;#video&#39;).css(&#39;display&#39;,&#39;none&#39;);
            $(&#39;#canvas&#39;).css(&#39;display&#39;,&#39;block&#39;);
            $(&#39;#showVideo&#39;).show();
        }
    })
//点击图片上传按钮
$(&#39;#uppicture&#39;).click(function () {
    var userId = $(&#39;.userId&#39;).val();
    var image_code = $(&#39;#image_code&#39;).val();//图片值
    if(!userId){
        alert(&#39;用户不存在&#39;);return;
    }
    if(!image_code){
        alert(&#39;请先拍照&#39;);return;
    }
    $.post("{:url(&#39;upPicture&#39;)}", {&#39;userId&#39;:userId,&#39;image_code&#39;:image_code}, function(res){
        // console.log(res);
        if(1 == res.code){
            layer.alert(res.msg, {title: &#39;友情提示&#39;, icon: 1});
            $(&#39;.picture&#39;).val(1);
        }else{
            layer.alert(res.msg, {title: &#39;友情提示&#39;, icon: 2});
        }
    });
});
</script>
Copy after login

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(&#39;image_code&#39;);
        if(empty($image_code)){
            $this ->error(&#39;照片为空&#39;);
        }
        $uId = input(&#39;userId&#39;);
       //处理接收过来的图片
        $img = str_replace(&#39;data:image/png;base64,&#39;, &#39;&#39;, $image_code);
        $img = str_replace(&#39; &#39;, &#39;+&#39;, $img);
        $data = base64_decode($img);
       // 图片名称
        $file_name = "./uploads/head/".time().".png";
        $fp = fopen($file_name, &#39;w&#39;);
        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(&#39;编辑成功!&#39;);
       }else{
           $this ->error(&#39;编辑失败,请刷新重试!&#39;);
       }
    }
Copy after login

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!

Related labels:
php
source:csdn.net
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template