ZXING与二维码

作者: MacSam | 来源:发表于2016-05-18 11:34 被阅读1057次

    在现在的网站开发中,难免会遇到要生成二维码的情况,比如要使用网页版的微信支付什么的.这里笔者分享一个java生成二维码的demo,这里使用到的是google的zxing,你可以在github上找到源码.

    • 你需要引入zxing的jar包,如果是maven工程.
    <dependency>   
         <groupId>com.google.zxing</groupId>   
         <artifactId>core</artifactId>  
         <version>3.2.1</version>
    </dependency>
    
    • 后台:在你的controller中放入以下方法,访问 YOUR-PATH/qr即可
        //[测试] 二维码url
        @RequestMapping("/qr")
        public String testQRCode(Model model) {    
              //这里随便给了一个微信支付相关的url
              model.addAttribute("code_url", "weixin://wxpay/bizpayurl?pr=PbcM89o");    
              //返回qr.html
              return "qr";
        }
    
        //显示二维码图片, 这个地址配在img的src下
        @RequestMapping("/qr-img")
        @ResponseBody
        public void getQRCode(String code_url, HttpServletResponse response) {   
             encodeQrcode(code_url, response);
        }
    
        //不保存二维码图片,以流的形式返回
        private void encodeQrcode(String content, HttpServletResponse response) {    
            if (StringUtils.isEmpty(content))        return;    
            MultiFormatWriter multiFormatWriter = new MultiFormatWriter();    
            Map hints = new HashMap();    
            //设置字符集编码类型  
            hints.put(EncodeHintType.CHARACTER_SET, "UTF-8"); 
            //设置二维码四周的白色边框 ,默认是4,默认为4的时候白色边框实在是太粗了   
            hints.put(EncodeHintType.MARGIN, 0);
            BitMatrix bitMatrix = null;    
            try {        
                    bitMatrix = multiFormatWriter.encode(content, BarcodeFormat.QR_CODE, 190, 190, hints);      
                    BufferedImage image = MatrixToImageWriter.toBufferedImage(bitMatrix);   
                    //输出二维码图片流      
                    try {          
                          ImageIO.write(image, "png", response.getOutputStream());     
                         } catch (IOException e) {       
                               // TODO Auto-generated catch block      
                                e.printStackTrace();    
                               }  
                         } catch (WriterException e1) {     
                               // TODO Auto-generated catch block       
                               e1.printStackTrace();   
                         }
      }
    
    • qr.html
    <!DOCTYPE html>
    <html lang="en">
    <head>   
          <meta charset="UTF-8"/>    
          <title></title>
    </head>
    <body>
          <!--The thymeleaf syntax is used here,you need to write your own path-->
          <img data-th-src="|${e.front('/qr-img')}?code_url=${code_url}|" style="width:300px;height:300px;"/>
    </body>
    </html>
    
    • 写到这里你会发现好像少了一个MatrixToImageWriter类,这个类是由google提供,直接copy一份即可
    package com.balabala.poet.base.utils;
    import com.google.zxing.common.BitMatrix;
    import javax.imageio.ImageIO;
    import java.awt.image.BufferedImage;
    import java.io.File;
    import java.io.IOException;
    import java.io.OutputStream;
    /** 
       * 二维码的生成需要借助MatrixToImageWriter类,该类是由Google提供的,可以将该类直接拷贝到源码中使用 
       * Created by sam on 16/4/12. 
       */
    public class MatrixToImageWriter {    
          private static final int BLACK = 0xFF000000;  
          private static final int WHITE = 0xFFFFFFFF;  
    
          private MatrixToImageWriter() {   
          }    
    
          public static BufferedImage toBufferedImage(BitMatrix matrix) {      
                int width = matrix.getWidth();     
                int height = matrix.getHeight();     
                BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);     
                for (int x = 0; x < width; x++) {       
                     for (int y = 0; y < height; y++) {     
                         image.setRGB(x, y, matrix.get(x, y) ? BLACK : WHITE);       
                     }  
                }       
                 return image;
          }    
      
          public static void writeToFile(BitMatrix matrix, String format, File file) throws IOException {   
                 BufferedImage image = toBufferedImage(matrix);       
                 if (!ImageIO.write(image, format, file)) {    
                       throw new IOException("Could not write an image of format " + format + " to " + file);
                }   
           } 
      
          public static void writeToStream(BitMatrix matrix, String format, OutputStream stream) throws IOException {    
               BufferedImage image = toBufferedImage(matrix);    
               if (!ImageIO.write(image, format, stream)) { 
                     throw new IOException("Could not write an image of format " + format);       
               } 
         }
    }
    

    相关文章

      网友评论

        本文标题:ZXING与二维码

        本文链接:https://www.haomeiwen.com/subject/rycwrttx.html