您好,登錄后才能下訂單哦!
本文實例為大家分享了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" ></canvas> <input id="snapBtn" type="button" value="拍照" /> <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>
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持億速云。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。