ZXing 初步使用

来源:互联网 发布:类似好奇心日报 知乎 编辑:程序博客网 时间:2024/05/16 08:54

@(JAVA开发)

Zxing 学习和使用

初步了解zxing

二维码现在已经非常普及,无论是网站还是移动端,都离不开二维码。所以掌握一两种二维码运用还是必要的。

代码段

/** * 展示生成二维码 * * @param response * * @param code *            二维码内容 * @param width *            生成的图片宽度 * @param height *            生成的图片高度 */@RequestMapping( "/showQRCode")public void showQRCode(HttpServletResponse response, QRCodeVo code) {    logger.info("-----Controller:showQRCode start ----" );    // 通过response返回给客户端    response.setHeader( "Pragma", "No-cache" );    response.setHeader( "Cache-Control", "no-cache" );    response.setDateHeader( "Expires", 0);    response.setContentType( "image/png"); //设置返回的是图片格式    int size = 250;    String fileType = "png";    OutputStream ops = null;    String content = code.createQRCodeContent();//实体类 规范输出的数据 这个可以不定义 ,但建议定义好     // ZXing采用Hashtable方式来保存设置参数,在这程瑞设置的是map 也可以    Map<EncodeHintType, Object> hintMap = new EnumMap<EncodeHintType, Object>(EncodeHintType.class);           //设置编码    hintMap.put(EncodeHintType. CHARACTER_SET, "UTF-8" );    // Now with zxing version 3.2.1 you could change border size (white    // border size to just 1)        //设置间距    hintMap.put(EncodeHintType. MARGIN, 1);            //设置纠错级别    hintMap.put(EncodeHintType. ERROR_CORRECTION, ErrorCorrectionLevel.L );    try {      //qr 对象 呈现二维码        QRCodeWriter qrCodeWriter = new QRCodeWriter();      //BitMatrix 根据其需要输出的参数,和设置条件等新建BitMatrix对象        BitMatrix byteMatrix = qrCodeWriter.encode(content, BarcodeFormat.QR_CODE , size, size, hintMap);        int CrunchifyWidth = byteMatrix.getWidth();      //BufferedImage的主要作用就是将一副图片加载到内存中        BufferedImage image = new BufferedImage(CrunchifyWidth, CrunchifyWidth, BufferedImage.TYPE_INT_RGB );        image.createGraphics();        Graphics2D graphics = (Graphics2D) image.getGraphics();        graphics.setColor(Color. WHITE);        graphics.fillRect(0, 0, CrunchifyWidth, CrunchifyWidth);        graphics.setColor(Color. BLACK);        for (int i = 0; i < CrunchifyWidth; i++) {            for (int j = 0; j < CrunchifyWidth; j++) {                if (byteMatrix.get(i, j)) {                    graphics.fillRect(i, j, 1, 1);                }            }        }        ops = response.getOutputStream();                     //将一个图像写入输出流        ImageIO. write(image, fileType, ops);        logger.info("-----Controller:showQRCode end ----" );    } catch (IOException e) {        logger.debug("----- showQRCode failure-----" , e);    } catch (WriterException e) {        logger.debug("----- showQRCode failure-----" , e);    }}

设置页面请求地址的链接为图片,这样当后台的图片流返回的时候就会在前台展现为一张二维码了。

0 0