Java使用Google Zxing生成二维码的例子

2025-05-29 0 26

以前只用过jQuery.qrcode生成过二维码,这次使用的是Google的zxing通过Java代码生成二维码并以流的方式输出到前台页面

所需jar包:zxing-3.2.1.jar

代码

前台展示页面

?

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
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>

<%

String path = request.getContextPath();

String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";

%>

<!DOCTYPE html>

<html>

<head>

<title>二维码</title>

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">

<script src="http://apps.bdimg.com/libs/jquery/1.9.1/jquery.min.js"></script>

<style>

body{text-align:center;}

</style>

</head>

<body>

请输入关键字,多个关键字请用逗号隔开

</br>

</br>

<textarea id="ids" cols="30" rows="10">

</textarea>

</br>

<button onclick="submit1()" value="提交">提交</button>

</br>

</br>

</br>

<div id="img">

</div>

<script>

function submit1() {

var reg = new RegExp(",","g");//替换所有","

var ids = $("#ids").val().replace(reg,",").split(",");

var html = "<table align=\\"center\\">";

for(var i = 0; i<ids.length; i++){

html += "<tr><td>" + ids[i] + "</td></tr>"

html += "<tr><td><img src=\\"<%=basePath%>qrCode/generateOneqrCode/?id=" + ids[i] + "\\" /></td></tr>";

}

html += "</table>";

$("#img").html(html);

}

</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
/**

* 生成一个二维码

* @param resp

* @param id

*/

@Override

public void generateOneqrCode(HttpServletResponse resp, String id) {

if (TextUtil.isNotEmpty(id)) {

ServletOutputStream stream = null;

try {

int width = 200;//图片的宽度

int height = 200;//图片的高度

stream = resp.getOutputStream();

QRCodeWriter writer = new QRCodeWriter();

BitMatrix m = writer.encode(id, BarcodeFormat.QR_CODE, height, width);

//以流的方式输出到前台,action中return null就可以

MatrixToImageWriter.writeToStream(m, "png", stream);

} catch (IOException e) {

e.printStackTrace();

} catch (WriterException e1) {

e1.printStackTrace();

} finally {

if (stream != null) {

try {

stream.flush();

stream.close();

} catch (IOException e) {

e.printStackTrace();

}

}

}

}

}

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持快网idc。

原文链接:https://segmentfault.com/a/1190000008523639

收藏 (0) 打赏

感谢您的支持,我会继续努力的!

打开微信/支付宝扫一扫,即可进行扫码打赏哦,分享从这里开始,精彩与您同在
点赞 (0)

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。

快网idc优惠网 建站教程 Java使用Google Zxing生成二维码的例子 https://www.kuaiidc.com/118365.html

相关文章

发表评论
暂无评论