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)

Oct 10, 2018 pm 05:51 PM
html5 web QR code scanning

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!

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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

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

Hot Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1665
14
PHP Tutorial
1269
29
C# Tutorial
1249
24
Table Border in HTML Table Border in HTML Sep 04, 2024 pm 04:49 PM

Guide to Table Border in HTML. Here we discuss multiple ways for defining table-border with examples of the Table Border in HTML.

Nested Table in HTML Nested Table in HTML Sep 04, 2024 pm 04:49 PM

This is a guide to Nested Table in HTML. Here we discuss how to create a table within the table along with the respective examples.

HTML margin-left HTML margin-left Sep 04, 2024 pm 04:48 PM

Guide to HTML margin-left. Here we discuss a brief overview on HTML margin-left and its Examples along with its Code Implementation.

HTML Table Layout HTML Table Layout Sep 04, 2024 pm 04:54 PM

Guide to HTML Table Layout. Here we discuss the Values of HTML Table Layout along with the examples and outputs n detail.

HTML Input Placeholder HTML Input Placeholder Sep 04, 2024 pm 04:54 PM

Guide to HTML Input Placeholder. Here we discuss the Examples of HTML Input Placeholder along with the codes and outputs.

HTML Ordered List HTML Ordered List Sep 04, 2024 pm 04:43 PM

Guide to the HTML Ordered List. Here we also discuss introduction of HTML Ordered list and types along with their example respectively

HTML onclick Button HTML onclick Button Sep 04, 2024 pm 04:49 PM

Guide to HTML onclick Button. Here we discuss their introduction, working, examples and onclick Event in various events respectively.

Moving Text in HTML Moving Text in HTML Sep 04, 2024 pm 04:45 PM

Guide to Moving Text in HTML. Here we discuss an introduction, how marquee tag work with syntax and examples to implement.

See all articles