一区二区三区在线-一区二区三区亚洲视频-一区二区三区亚洲-一区二区三区午夜-一区二区三区四区在线视频-一区二区三区四区在线免费观看

服務(wù)器之家:專注于服務(wù)器技術(shù)及軟件下載分享
分類導(dǎo)航

PHP教程|ASP.NET教程|Java教程|ASP教程|編程技術(shù)|正則表達(dá)式|C/C++|IOS|C#|Swift|Android|VB|R語言|JavaScript|易語言|vb.net|

服務(wù)器之家 - 編程語言 - Java教程 - java實(shí)現(xiàn)電腦端掃描二維碼

java實(shí)現(xiàn)電腦端掃描二維碼

2021-06-04 13:57秋波蓮月 Java教程

這篇文章主要為大家詳細(xì)介紹了java實(shí)現(xiàn)電腦端掃描二維碼,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下

本文實(shí)例為大家分享了java實(shí)現(xiàn)電腦端掃描二維碼的具體代碼,供大家參考,具體內(nèi)容如下

說明:js調(diào)去電腦攝像頭拍照,然后獲取圖片base64位編碼,再將base64為編碼轉(zhuǎn)為bolb,通過定時(shí)異步上傳到后臺(tái),在后臺(tái)對(duì)圖片文件進(jìn)行解碼,返回解碼結(jié)果到頁面,然后頁面重新加載結(jié)果(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>
<!-- 這個(gè)應(yīng)該是需要的 -->
<script type="text/javascript" src="${basepath}js/jquery.qrcode.min.js"></script>

后臺(tái)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>

后臺(tái)代碼處理方式:

?
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");
     // 解碼設(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代碼:

第一種處理方式:

?
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.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無參數(shù)的構(gòu)造函數(shù)
        var formdata = new formdata();  //這里連帶form里的其他參數(shù)也一起提交了,如果不需要提交其他參數(shù)可以直接formdata無參數(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>

第二種處理方式:

?
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.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("用戶拒絕了瀏覽器請(qǐng)求媒體的權(quán)限");
          }
           //console.log("用戶拒絕了瀏覽器請(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("指定的媒體類型未接收到媒體流");
          }
           //console.log("指定的媒體類型未接收到媒體流",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無參數(shù)的構(gòu)造函數(shù)
    var formdata = new formdata();  //這里連帶form里的其他參數(shù)也一起提交了,如果不需要提交其他參數(shù)可以直接formdata無參數(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í)有所幫助,也希望大家多多支持服務(wù)器之家。 

原文鏈接:https://blog.csdn.net/u012883078/article/details/81067387?utm_source=blogxgwz0

延伸 · 閱讀

精彩推薦
主站蜘蛛池模板: 亚洲视频第一页 | 99精品视频在线观看 | 亚洲成人伦理 | 美女无遮挡 | 天堂网www在线观看 天堂欧美 | 亚洲日本视频在线 | 成年人视频在线免费看 | 香蕉久久一区二区不卡无毒影院 | 暖暖视频高清图片免费完整版 | 非洲黑人bbwbbwbbw | 国产欧美另类久久精品91 | 国产一卡2卡3卡四卡国色天香 | 2021海角社区最新版 | 小SAO货叫大声点妓女 | 精品在线播放 | 免费看a视频 | 国产精品视频久久久 | 91亚洲精品久久91综合 | 亚洲AV精品无码喷水直播间 | 高清女主播一区二区三区 | 5x社区在线观看直接进入 | 色老板最新网站视频地址 | 日本精品中文字幕在线播放 | 蛮荒的童话未删减在线观看 | 被老外玩爽的中国美女视频 | 免费我看视频在线观看 | 成人无高清96免费 | xxoo好深好爽动态 | 国产成人精品日本亚洲网址 | 性柔术xxxhd 性派对videos18party | 日本又黄又裸一级大黄裸片 | jizzjizz大学生| 日本黄色一区 | a片毛片在线免费看 | 4444亚洲国产成人精品 | 欧美精品一国产成人性影视 | 青柠影院在线观看免费完整版1 | 午夜爽喷水无码成人18禁三级 | 国产精品久久久久久久久 | 9999视频 | 236zz宅宅最新伦理 |