本文實(shí)例為大家分享了java實(shí)現(xiàn)電腦端掃描二維碼的具體代碼,供大家參考,具體內(nèi)容如下
說(shuō)明:js調(diào)去電腦攝像頭拍照,然后獲取圖片base64位編碼,再將base64為編碼轉(zhuǎn)為bolb,通過(guò)定時(shí)異步上傳到后臺(tái),在后臺(tái)對(duì)圖片文件進(jìn)行解碼,返回解碼結(jié)果到頁(yè)面,然后頁(yè)面重新加載結(jié)果(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><!-- 這個(gè)應(yīng)該是需要的 --><script type="text/javascript" src="${basePath}js/jquery.qrcode.min.js"></script>
后臺(tái)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>
后臺(tái)代碼處理方式:
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"); // 解碼設(shè)置編碼方式為: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; }
前臺(tái)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碼設(shè)置給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里的其他參數(shù)也一起提交了,如果不需要提交其他參數(shù)可以直接FormData無(wú)參數(shù)的構(gòu)造函數(shù) var formData = new FormData(); //這里連帶form里的其他參數(shù)也一起提交了,如果不需要提交其他參數(shù)可以直接FormData無(wú)參數(shù)的構(gòu)造函數(shù) //convertBase64UrlToBlob函數(shù)是將base64編碼轉(zhuǎn)換為Blob formData.append("ewmImg",convertBase64UrlToBlob(base64Codes)); //append函數(shù)的第一個(gè)參數(shù)是后臺(tái)獲取數(shù)據(jù)的參數(shù)名,和html標(biāo)簽的input的name屬性功能相同 //ajax 提交form $.ajax({ url : '${urlPath}query/decodeEwm', type : "POST", data : formData, dataType:"text", processData : false, // 告訴jQuery不要去處理發(fā)送的數(shù)據(jù) contentType : false, // 告訴jQuery不要去設(shè)置Content-Type請(qǐng)求頭 success:function(data){ //alert(data); if(data != "no"){ window.location.href=data; } }, xhr:function(){ //在jquery函數(shù)中直接使用ajax的XMLHttpRequest對(duì)象 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() + '%'); //在控制臺(tái)打印上傳進(jìn)度 } }, false); return xhr; } }); } /** * 將以base64的圖片url數(shù)據(jù)轉(zhuǎn)換為Blob * @param urlData * 用url方式表示的base64圖片數(shù)據(jù) */ function convertBase64UrlToBlob(urlData){ var bytes=window.atob(urlData.split(',')[1]); //去掉url的頭,并轉(zhuǎn)換為byte //處理異常,將ascii碼小于0的轉(zhuǎn)換為大于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><!-- 這個(gè)應(yīng)該是需要的 --><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("用戶(hù)拒絕了瀏覽器請(qǐng)求媒體的權(quán)限"); } //console.log("用戶(hù)拒絕了瀏覽器請(qǐng)求媒體的權(quán)限",error.code); if(error.NOT_SUPPORTED_ERROR){ alert("當(dāng)前瀏覽器不支持拍照功能"); } //console.log("當(dāng)前瀏覽器不支持拍照功能",error.code); if(error.MANDATORY_UNSATISFIED_ERROR){ alert("指定的媒體類(lèi)型未接收到媒體流"); } //console.log("指定的媒體類(lèi)型未接收到媒體流",error.code); alert("Video capture error: " + error.code); } ); //定時(shí)掃描 setInterval(function () { context.drawImage(video, 0, 0, canvas.width = video.videoWidth, canvas.height = video.videoHeight); sumitImageFile(canvas.toDataURL()); }, 1500); } else { alert("掃描出錯(cuò),換種方式試試!"); } }, false); /** * @param base64Codes * 圖片的base64編碼 */ function sumitImageFile(base64Codes){ // var form=document.forms[0]; // var formData = new FormData(form); //這里連帶form里的其他參數(shù)也一起提交了,如果不需要提交其他參數(shù)可以直接FormData無(wú)參數(shù)的構(gòu)造函數(shù) var formData = new FormData(); //這里連帶form里的其他參數(shù)也一起提交了,如果不需要提交其他參數(shù)可以直接FormData無(wú)參數(shù)的構(gòu)造函數(shù) //convertBase64UrlToBlob函數(shù)是將base64編碼轉(zhuǎn)換為Blob formData.append("ewmImg",convertBase64UrlToBlob(base64Codes)); //append函數(shù)的第一個(gè)參數(shù)是后臺(tái)獲取數(shù)據(jù)的參數(shù)名,和html標(biāo)簽的input的name屬性功能相同 //ajax 提交form $.ajax({ url : '${urlPath}query/decodeEwm', type : "POST", data : formData, dataType:"text", processData : false, // 告訴jQuery不要去處理發(fā)送的數(shù)據(jù) contentType : false, // 告訴jQuery不要去設(shè)置Content-Type請(qǐng)求頭 success:function(data){ //alert(data); if(data != "no"){ window.location.href=data; } }, xhr:function(){ //在jquery函數(shù)中直接使用ajax的XMLHttpRequest對(duì)象 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() + '%'); //在控制臺(tái)打印上傳進(jìn)度 } }, false); return xhr; } }); } /** * 將以base64的圖片url數(shù)據(jù)轉(zhuǎn)換為Blob * @param urlData * 用url方式表示的base64圖片數(shù)據(jù) */ function convertBase64UrlToBlob(urlData){ var bytes=window.atob(urlData.split(',')[1]); //去掉url的頭,并轉(zhuǎn)換為byte //處理異常,將ascii碼小于0的轉(zhuǎn)換為大于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>
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持VeVb武林網(wǎng)。
新聞熱點(diǎn)
疑難解答
圖片精選