Home > Web Front-end > H5 Tutorial > web/html5 calls the camera to achieve the QR code scanning effect (code example)

web/html5 calls the camera to achieve the QR code scanning effect (code example)

青灯夜游
Release: 2018-10-10 17:51:07
forward
22471 people have browsed it

This article will introduce how to use web/html5 to call the camera to achieve the effect of QR code scanning. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

Use html5 (navigator.getUserMedia) to call the camera to capture the image media stream, and call the java interface to parse the image QR code through php to achieve QR code analysis, which can be combined with your own business! However, there are currently not many supported browsers, which is a problem.

html/js

nbsp;html>

	<title>HTML5 code Reader</title>
	<meta>

<style>
 html, body { height: 100%; width: 100%; text-align:center; }  
</style>
<script></script>
<script>
//这段代 主要是获取摄像头的视频流并显示在Video 签中  
var canvas=null,context=null,video=null;   
window.addEventListener("DOMContentLoaded", function ()
{
	try{
		canvas = document.getElementById("canvas");
		context = canvas.getContext("2d");
		video = document.getElementById("video");
		
		var videoObj = { "video": true,audio:false},
		flag=true,
		MediaErr = function (error)
		{           
			flag=false;  
			if (error.PERMISSION_DENIED)
			{
				 alert(&#39;用户拒绝了浏览器请求媒体的权限&#39;, &#39;提示&#39;);
			} else if (error.NOT_SUPPORTED_ERROR) {
				 alert(&#39;对不起,您的浏览器不支持拍照功能,请使用其他浏览器&#39;, &#39;提示&#39;);
			} else if (error.MANDATORY_UNSATISFIED_ERROR) {
				 alert(&#39;指定的媒体类型未接收到媒体流&#39;, &#39;提示&#39;);
			} else {
				 alert(&#39;系统未能获取到摄像头,请确保摄像头已正确安装。或尝试刷新页面,重试&#39;, &#39;提示&#39;);
			}
		};
		//获取媒体的兼容代码,目前只支持(Firefox,Chrome,Opera)
        if (navigator.getUserMedia)
		{
			//qq浏览器不支持
			if (navigator.userAgent.indexOf(&#39;MQQBrowser&#39;) > -1) {
				 alert(&#39;对不起,您的浏览器不支持拍照功能,请使用其他浏览器&#39;, &#39;提示&#39;);
				 return false;
            }
            navigator.getUserMedia(videoObj, function (stream) {
				video.src = stream;                
				video.play();      
            }, MediaErr);           
		}
		else if(navigator.webkitGetUserMedia)
		{
           navigator.webkitGetUserMedia(videoObj, function (stream)
		   {          
             video.src = window.webkitURL.createObjectURL(stream);           
             video.play();           
        	}, MediaErr);           
		}
		else if (navigator.mozGetUserMedia)
		{
			navigator.mozGetUserMedia(videoObj, function (stream) {
				 video.src = window.URL.createObjectURL(stream);
				 video.play();
			}, MediaErr);
		}
		else if (navigator.msGetUserMedia)
		{ 
			 navigator.msGetUserMedia(videoObj, function (stream) {
             	$(document).scrollTop($(window).height());
                video.src = window.URL.createObjectURL(stream);
                video.play();
             }, MediaErr);
		}else{
			alert(&#39;对不起,您的浏览器不支持拍照功能,请使用其他浏览器&#39;);
			return false;
		}
		if(flag){
			alert(&#39;为了获得更准确的测试结果,请尽量将二维码置于框中,然后进行拍摄、扫描。 请确保浏览器有权限使用摄像功能&#39;);
		}
     	 //这个是拍照按钮的事件,          
     	$("#snap").click(function () {startPat();}).show();
	}catch(e){      
        printHtml("浏览器不支持HTML5 CANVAS");       
    } 
}, false);
    
//打印内容到页面      
function printHtml(content){
	$(window.document.body).append(content+"<br/>");
}
//开始拍照
function startPat(){
	setTimeout(function(){//防止调用过快
		if(context)
		{
			context.drawImage(video, 0, 0, 320, 320);     
			CatchCode(); 
		}
	},200);
} 
//抓屏获取图像流,并上传到服务器      
function CatchCode() {        
	if(canvas!=null)
	{  
   		//以下开始编 数据   
		var imgData = canvas.toDataURL(); 
		//将图像转换为base64数据
        var base64Data = imgData;//.substr(22); //在前端截取22位之后的字符串作为图像数据
        //开始异步上
	   $.post("saveimg.php", { "img": base64Data },function (result)
	   {   
			printHtml("解析结果:"+result.data);
			if (result.status == "success" && result.data!="")
			{                 
				printHtml("解析结果成功!");
			}else{  
				startPat();//如果没有解析出来则重新抓拍解析       
			}
	   },"json");
	}
}      
</script>
  

<p></p>
<p>       
<video>
</video>       
<canvas>
</canvas> <br>
<button>开始扫描</button>  
   </p>



Copy after login

php(saveimg)

##

<?php include_once("utils.php");
$base64_image_content=$_POST[&#39;img&#39;];
if (preg_match(&#39;/^(data:\s*image\/(\w+);base64,)/&#39;, $base64_image_content, $result))
{
  $type = $result[2];
  $new_file = "./2.{$type}";
  if (file_put_contents($new_file, base64_decode(str_replace($result[1], &#39;&#39;, $base64_image_content)))){
	$code=utils::deCodeBitMap("2.png","192.168.46.123",20147);
	echo &#39;{"status":"success","data":"&#39;.trim($code).&#39;"}&#39;;
  }else{
  	echo &#39;{"status":"write error","data":"NO"}&#39;;
  }
}else{
	echo &#39;{"status":"preg error","data":"NO"}&#39;;
}
?>
Copy after login
php(utils)

 class  utils{
 	
	/**
     	* @access static
     	* @param  $imagepath String 图片的完整路径
	* @param  $host      String 主机如:127.0.0.1
	* @param  $port      String 端口号如:20147
     	* @return string 解析出的URL
    	*/
	static function deCodeBitMap($imagepath,$host,$port){
		$socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP) or die($imagepath." Could not connet server create\n"); // 创建一个Socket
		if(!$socket){
			return "";
		}
		$connection = socket_connect($socket, $host, $port) or die($imagepath." Could not connet server connection\n");    //  连接
		if(!$connection){
			return "";
		}
		socket_write($socket, $imagepath) or die("Write failed\n"); // 数据传送 向服务器发送消息

		$buff = socket_read($socket, 1024, PHP_NORMAL_READ);
		return $buff;
	}
	
 }
Copy after login
java extension usage instructions

This parsing process requires java environment support. After the jar package is started, The 20147 port of this machine accepts socket monitoring, so it can be called by any network programming language. 1 Start the jar package from the command line
java -jar xxxxx.jar
If the startup is successful, you should be able to see the application of port 20147
2 Service socket call
The PHP calling code is temporarily provided

Final effect:

web/html5 calls the camera to achieve the QR code scanning effect (code example)

##Browser support

web/html5 calls the camera to achieve the QR code scanning effect (code example)Summary: The above is the entire content of this article, I hope it will be helpful to everyone's study. For more related tutorials, please visit

Html5 Video Tutorial

! Related recommendations:

php public welfare training video tutorial

The above is the detailed content of web/html5 calls the camera to achieve the QR code scanning effect (code example). For more information, please follow other related articles on the PHP Chinese website!

Related labels:
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