本文实例为大家分享了java实现电脑端扫描二维码的具体代码,供大家参考,具体内容如下
说明:js调去电脑摄像头拍照,然后获取图片base64位编码,再将base64为编码转为bolb,通过定时异步上传到后台,在后台对图片文件进行解码,返回解码结果到页面,然后页面重新加载结果(url)
第一种方式引入js
1 2 |
<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
1 2 3 |
<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包
1 2 3 4 5 6 7 8 9 10 11 |
<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> |
后台代码处理方式:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 |
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代码:
第一种处理方式:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 |
<%@ page contenttype= "text/html; charset=utf-8" %> <%@ taglib prefix= "c" uri= "http://java.sun测试数据/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> |
第二种处理方式:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 |
<%@ page contenttype= "text/html; charset=utf-8" %> <%@ taglib prefix= "c" uri= "http://java.sun测试数据/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> |
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。
原文链接:https://blog.csdn.net/u012883078/article/details/81067387?utm_source=blogxgwz0