Flask接口签名sign原理与实例代码浅析
439
2023-01-21
java实现电脑端扫描二维码
本文实例为大家分享了java实现电脑端扫描二维码的具体代码,供大家参考,具体内容如下
说明:js调去电脑摄像头拍照,然后获取图片base64位编码,再将base64为编码转为bolb,通过定时异步上传到后台,在后台对图片文件进行解码,返回解码结果到页面,然后页面重新加载结果(url)
第一种方式引入js
第二种方式引入js
后台java代码maven引入jar包
后台代码处理方式:
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));
finTTSHMEFal Map
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);
%>
#webcam {
width: auto;
height: auto;
float: left;
}
#base64image {
display: block;
http:// width: 320px;
height: 240px;
}
$(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'});
}
第二种处理方式:
<%@ 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);
%>
版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。
发表评论
暂时没有评论,来抢沙发吧~