使用ZXing生成QRcode二维码

来源:互联网 发布:苹果电脑激活windows 编辑:程序博客网 时间:2024/06/07 13:50

生成二维码的方法很多,但是我感觉还是Google的ZXing生成比较简单的。

1.首先先下载google的包ZXing3.2.1.jar   ,把包导入到项目中。

2.开始代码

2.1.生成二维码:

 /**     * 生成     */    @Test    public  void createQRBarcode(){        int width = 300;        int heigth = 300;        String format = "png";//生成的格式        String content = "http://blog.csdn.net/chentao866";//二维码内容        //定义二维码参数        HashMap hints = new HashMap();        hints.put(EncodeHintType.CHARACTER_SET,"utf-8");//设置编码格式        hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.M);//设置纠错等级        hints.put(EncodeHintType.MARGIN,3);//设置边距        try {            BitMatrix matrix = new MultiFormatWriter().encode(content, BarcodeFormat.QR_CODE,width,heigth,hints);            Path file = new File("D://11.png").toPath();            MatrixToImageWriter.writeToPath(matrix,format,file);        } catch (Exception e) {            e.printStackTrace();        }    }

2.2解析二维码:

  /**     * 解析     */    @Test    public  void decodeQRBarcode(){        try {            MultiFormatReader multiFormatReader = new MultiFormatReader();//解析对象            File file = new File("D://11.png");            BufferedImage image = ImageIO.read(file);//把文件识别成一个图片            BinaryBitmap binaeyBitmap = new BinaryBitmap(new HybridBinarizer(new BufferedImageLuminanceSource(image)));            HashMap hints = new HashMap();            hints.put(EncodeHintType.CHARACTER_SET,"utf-8");//设置编码格式            Result result = multiFormatReader.decode(binaeyBitmap,hints);            System.out.println("二维码的格式:"+result.getBarcodeFormat());            System.out.println("二维码的内容:"+result.getText());            System.out.println("解析结果:"+result.toString());        } catch (Exception e) {            e.printStackTrace();        }    }

   a.读取二维码图片,并送给 Zxing LuminanceSource 和 Binarizer 两兄弟的处理。

   b.处理完的位图和相应的解析参数,交由 MultiFormatReader 处理,并返回解析后的结果。


原创粉丝点击