使用Google Zxing生成二維碼的例子

之前只用過jQuery.qrcode生成過二維碼,此次使用的是Googlezxing經過Java代碼生成二維碼並以流的方式輸出到前臺頁面
所需jar包:zxing-3.2.1.jarhtml

代碼

前臺展現頁面

<%@ 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>

後臺主要代碼

/**
     * 生成一個二維碼
     * @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();
                    }
                }
            }
        }
    }
相關文章
相關標籤/搜索