本文实例为大家分享了java实现电脑端扫描二维码的具体代码,供大家参考,具体内容如下
说明:js调去电脑摄像头拍照,然后获取图片base64位编码,再将base64为编码转为bolb,通过定时异步上传到后台,在后台对图片文件进行解码,返回解码结果到页面,然后页面重新加载结果(url)
第一种方式引入js
<script type="text/javascript" src="${basePath}js/jquery-1.9.min.js"></script><script type="text/javascript" src="${basePath}js/jquery.webcam.min.js"></script>
第二种方式引入js
<script type="text/javascript" src="${basePath}js/jquery-1.9.min.js"></script><!-- 这个应该是需要的 --><script type="text/javascript" src="${basePath}js/jquery.qrcode.min.js"></script>
后台java代码maven引入jar包
<dependency> <groupId>com.github.binarywang</groupId> <artifactId>qrcode-utils</artifactId> <version>1.1</version> </dependency> <dependency> <groupId>com.google.zxing</groupId> <artifactId>core</artifactId> <version>3.3.3</version> </dependency>
后台代码处理方式:
public class EwmDescode { /** * 解析二维码 * * @param input * 二维码输入流 */ public static final String parse(InputStream input) throws Exception { Reader reader = null; BufferedImage image; try { image = ImageIO.read(input); if (image == null) { throw new Exception("cannot read image from inputstream."); } final LuminanceSource source = new BufferedImageLuminanceSource(image); final BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source)); final Map<DecodeHintType, String> hints = new HashMap<DecodeHintType, String>(); hints.put(DecodeHintType.CHARACTER_SET, "utf-8"); // 解码设置编码方式为:utf-8, reader = new MultiFormatReader(); return reader.decode(bitmap, hints).getText(); } catch (IOException e) { e.printStackTrace(); throw new Exception("parse QR code error: ", e); } catch (ReaderException e) { e.printStackTrace(); throw new Exception("parse QR code error: ", e); } } /** * 解析二维码 * * @param url * 二维码url */ public static final String parse(URL url) throws Exception { InputStream in = null; try { in = url.openStream(); return parse(in); } catch (IOException e) { e.printStackTrace(); throw new Exception("parse QR code error: ", e); } finally { IOUtils.closeQuietly(in); } } /** * 解析二维码 * * @param file * 二维码图片文件 */ public static final String parse(File file) throws Exception { InputStream in = null; try { in = new BufferedInputStream(new FileInputStream(file)); return parse(in); } catch (FileNotFoundException e) { e.printStackTrace(); throw new Exception("parse QR code error: ", e); } finally { IOUtils.closeQuietly(in); } } /** * 解析二维码 * * @param filePath * 二维码图片文件路径 */ public static final String parse(String filePath) throws Exception { InputStream in = null; try { in = new BufferedInputStream(new FileInputStream(filePath)); return parse(in); } catch (FileNotFoundException e) { e.printStackTrace(); throw new Exception("parse QR code error: ", e); } finally { IOUtils.closeQuietly(in); } } }@RequestMapping("/decodeEwm") @ResponseBody public String decodeEwm(MultipartFile ewmImg){ String parse = null; try { parse = EwmDescode.parse(ewmImg.getInputStream()); } catch (Exception e) { //e.printStackTrace(); } String msg = "no"; if(StringUtils.isNotBlank(parse)){ return parse; } return msg; }
前台jsp代码:
第一种处理方式:
<%@ page contentType="text/html; charset=utf-8"%><%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%><% String path = request.getContextPath(); String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + path + "/resources/"; String urlPath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + path + "/"; request.setAttribute("path", path); request.setAttribute("basePath", basePath); request.setAttribute("urlPath", urlPath);%><!DOCTYPE html><html> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <title>webcam</title> <style type="text/css"> #webcam { width: auto; height: auto; float: left; } #base64image { display: block; width: 320px; height: 240px; } </style> <!-- 基本的jquery引用,1.5版本以上 --> <script type="text/javascript" src="${basePath}js/jquery-1.9.min.js"></script> <!-- webcam插件引用 --> <script type="text/javascript" src="${basePath}js/jquery.webcam.min.js"></script> </head> <body> <div id="webcam"></div> <canvas id="canvas" width="320" height="240" style="display: none;"></canvas> <input id="snapBtn" type="button" value="拍照" style="display: none;"/> <img id="base64image" src='' /> <script type="text/javascript"> $(document).ready(function() { var pos = 0, ctx = null, image = []; var w = 320; var h = 240; jQuery("#webcam").webcam({ width: 320, height: 240, mode: "callback", swffile: "${basePath}js/jscam_canvas_only.swf", // 这里引入swf文件,注意路径 // swffile: "/jscam_canvas_only.swf", // 这里引入swf文件,注意路径 onTick: function(remain) {}, onSave: function(data) { var col = data.split(";"); var img = image; for(var i = 0; i < 320; i++) { var tmp = parseInt(col[i]); img.data[pos + 0] = (tmp >> 16) & 0xff; img.data[pos + 1] = (tmp >> 8) & 0xff; img.data[pos + 2] = tmp & 0xff; img.data[pos + 3] = 0xff; pos += 4; } if(pos >= 4 * 320 * 240) { // 将图片显示到canvas中 ctx.putImageData(img, 0, 0); sumitImageFile(canvas.toDataURL("image/png")); /* // 取得图片的base64码 var base64 = canvas.toDataURL("image/png"); // 将图片base64码设置给img var base64image = document.getElementById('base64image'); base64image.setAttribute('src', base64); */ pos = 0; } }, onCapture: function() { webcam.save(); // Show a flash for example }, debug: function(type, string) { console.log('type:' + type + ',string:' + string); // Write debug information to console.log() or a div }, onLoad: function() { // Page load } }); window.addEventListener("load", function() { var canvas = document.getElementById("canvas"); if(canvas.getContext) { ctx = canvas.getContext("2d"); ctx.clearRect(0, 0, 320, 240); var img = new Image(); img.onload = function() { ctx.drawImage(img, 129, 89); } image = ctx.getImageData(0, 0, 320, 240); } }, false); $('#snapBtn').on('click', function() { webcam.capture(); }); }); setInterval(function () { $("#snapBtn").click(); }, 1500); /** * @param base64Codes * 图片的base64编码 */ function sumitImageFile(base64Codes){ // var form=document.forms[0]; // var formData = new FormData(form); //这里连带form里的其他参数也一起提交了,如果不需要提交其他参数可以直接FormData无参数的构造函数 var formData = new FormData(); //这里连带form里的其他参数也一起提交了,如果不需要提交其他参数可以直接FormData无参数的构造函数 //convertBase64UrlToBlob函数是将base64编码转换为Blob formData.append("ewmImg",convertBase64UrlToBlob(base64Codes)); //append函数的第一个参数是后台获取数据的参数名,和html标签的input的name属性功能相同 //ajax 提交form $.ajax({ url : '${urlPath}query/decodeEwm', type : "POST", data : formData, dataType:"text", processData : false, // 告诉jQuery不要去处理发送的数据 contentType : false, // 告诉jQuery不要去设置Content-Type请求头 success:function(data){ //alert(data); if(data != "no"){ window.location.href=data; } }, xhr:function(){ //在jquery函数中直接使用ajax的XMLHttpRequest对象 var xhr = new XMLHttpRequest(); xhr.upload.addEventListener("progress", function(evt){ if (evt.lengthComputable) { var percentComplete = Math.round(evt.loaded * 100 / evt.total); console.log("正在提交."+percentComplete.toString() + '%'); //在控制台打印上传进度 } }, false); return xhr; } }); } /** * 将以base64的图片url数据转换为Blob * @param urlData * 用url方式表示的base64图片数据 */ function convertBase64UrlToBlob(urlData){ var bytes=window.atob(urlData.split(',')[1]); //去掉url的头,并转换为byte //处理异常,将ascii码小于0的转换为大于0 var ab = new ArrayBuffer(bytes.length); var ia = new Uint8Array(ab); for (var i = 0; i < bytes.length; i++) { ia[i] = bytes.charCodeAt(i); } return new Blob( [ab] , {type : 'image/png'}); } </script> </body> </html>
第二种处理方式:
<%@ page contentType="text/html; charset=utf-8"%><%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%><% String path = request.getContextPath(); String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + path + "/resources/"; String urlPath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + path + "/"; request.setAttribute("path", path); request.setAttribute("basePath", basePath); request.setAttribute("urlPath", urlPath);%><!DOCTYPE html><html><head><title>QRCODE</title></head><script type="text/javascript" src="${basePath}js/jquery-1.9.min.js"></script><!-- 这个应该是需要的 --><script type="text/javascript" src="${basePath}js/jquery.qrcode.min.js"></script><body><style>#video {display: block;margin:1em auto;width:280px;height:280px;}</style> <video id="video" autoplay></video><script> window.addEventListener("DOMContentLoaded", function () { var video = document.getElementById("video"), canvas, context; try { canvas = document.createElement("canvas"); context = canvas.getContext("2d"); } catch (e) { alert("not support canvas!"); return; } navigator.getUserMedia = navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia || navigator.msGetUserMedia; if (navigator.getUserMedia){ navigator.getUserMedia( { "video": true }, function (stream) { if (video.mozSrcObject !== undefined)video.mozSrcObject = stream; else video.src = ((window.URL || window.webkitURL || window.mozURL || window.msURL) && window.URL.createObjectURL(stream)) || stream; video.play(); }, function (error) { if(error.PERMISSION_DENIED){ alert("用户拒绝了浏览器请求媒体的权限"); } //console.log("用户拒绝了浏览器请求媒体的权限",error.code); if(error.NOT_SUPPORTED_ERROR){ alert("当前浏览器不支持拍照功能"); } //console.log("当前浏览器不支持拍照功能",error.code); if(error.MANDATORY_UNSATISFIED_ERROR){ alert("指定的媒体类型未接收到媒体流"); } //console.log("指定的媒体类型未接收到媒体流",error.code); alert("Video capture error: " + error.code); } ); //定时扫描 setInterval(function () { context.drawImage(video, 0, 0, canvas.width = video.videoWidth, canvas.height = video.videoHeight); sumitImageFile(canvas.toDataURL()); }, 1500); } else { alert("扫描出错,换种方式试试!"); } }, false); /** * @param base64Codes * 图片的base64编码 */ function sumitImageFile(base64Codes){ // var form=document.forms[0]; // var formData = new FormData(form); //这里连带form里的其他参数也一起提交了,如果不需要提交其他参数可以直接FormData无参数的构造函数 var formData = new FormData(); //这里连带form里的其他参数也一起提交了,如果不需要提交其他参数可以直接FormData无参数的构造函数 //convertBase64UrlToBlob函数是将base64编码转换为Blob formData.append("ewmImg",convertBase64UrlToBlob(base64Codes)); //append函数的第一个参数是后台获取数据的参数名,和html标签的input的name属性功能相同 //ajax 提交form $.ajax({ url : '${urlPath}query/decodeEwm', type : "POST", data : formData, dataType:"text", processData : false, // 告诉jQuery不要去处理发送的数据 contentType : false, // 告诉jQuery不要去设置Content-Type请求头 success:function(data){ //alert(data); if(data != "no"){ window.location.href=data; } }, xhr:function(){ //在jquery函数中直接使用ajax的XMLHttpRequest对象 var xhr = new XMLHttpRequest(); xhr.upload.addEventListener("progress", function(evt){ if (evt.lengthComputable) { var percentComplete = Math.round(evt.loaded * 100 / evt.total); console.log("正在提交."+percentComplete.toString() + '%'); //在控制台打印上传进度 } }, false); return xhr; } }); } /** * 将以base64的图片url数据转换为Blob * @param urlData * 用url方式表示的base64图片数据 */ function convertBase64UrlToBlob(urlData){ var bytes=window.atob(urlData.split(',')[1]); //去掉url的头,并转换为byte //处理异常,将ascii码小于0的转换为大于0 var ab = new ArrayBuffer(bytes.length); var ia = new Uint8Array(ab); for (var i = 0; i < bytes.length; i++) { ia[i] = bytes.charCodeAt(i); } return new Blob( [ab] , {type : 'image/png'}); } </script> </body> </html>
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持VeVb武林网。
注:相关教程知识阅读请移步到JAVA教程频道。