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

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

所需jar包:zxing-3.2.1.jar

代码

前台展示页面

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>



二维码





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





后台主要代码

/**
   * 生成一个二维码
   * @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();
          }
        }
      }
    }
  }

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

你可能感兴趣的:(Java使用Google Zxing生成二维码的例子)