java实现二维码生成

2018-06-06  本文已影响62人  老汉健身

二维码:

使用java生成二维码:

1.在Pom.xml中添加依赖的Jar包:

<dependency>

    <groupId>com.google.zxing</groupId>

    <artifactId>core</artifactId>

    <version>3.0.0</version>

</dependency>

<dependency>

    <groupId>com.google.zxing</groupId>

    <artifactId>javase</artifactId>

    <version>3.0.0</version>

</dependency>

2.生成二维码到指定的盘下面,这里以D盘为例:

/**

* 生成二维码测试

* @auther xpc 252645816@qq.com

* @date 2018/6/6 20:45

*/

public class Generate {

    public static void main(String[] args){

        String text ="www.17-53.com";

int width =100;

int height =100;

String format ="png";

Hashtable hints =new Hashtable();

//中文设置为utf-8

        hints.put(EncodeHintType.CHARACTER_SET,"utf-8");

//容错率 一般设置为M,设置的太高的话二维码里包含的内容量就会下降

        hints.put(EncodeHintType.ERROR_CORRECTION,ErrorCorrectionLevel.M);

//设置二维码边框,一般为2

        hints.put(EncodeHintType.MARGIN,2);

try {

            BitMatrix bitMatrix =new MultiFormatWriter().encode(text,BarcodeFormat.QR_CODE,width,height,hints);

Path file=new java.io.File("D:/cunjia.png").toPath();

MatrixToImageWriter.writeToPath(bitMatrix,format,file);

} catch (Exception e) {

            e.printStackTrace();

}

}

}

3.解析指定的二维码图片的内容

package com.imooc.code;

import com.google.zxing.*;

import com.google.zxing.client.j2se.BufferedImageLuminanceSource;

import com.google.zxing.common.HybridBinarizer;

import javax.imageio.ImageIO;

import java.awt.image.BufferedImage;

import java.io.File;

import java.io.IOException;

import java.util.Hashtable;

/**.

* 二维码解析

* @auther xpc 252645816@qq.com

* @date 2018/6/6 21:50

*/

public class Resolve {

    public static void main(String[] args) throws NotFoundException {

        MultiFormatReader formatReader=new MultiFormatReader();

File file =new File("D:/cunjia.png");

BufferedImage image=null;

try {

            image =ImageIO.read(file);

} catch (IOException e) {

            e.printStackTrace();

}

        BinaryBitmap binaryBitmap =new BinaryBitmap(new HybridBinarizer(new BufferedImageLuminanceSource(image)));

Hashtable hints=new Hashtable();

hints.put(EncodeHintType.CHARACTER_SET,"utf-8");

Result result=formatReader.decode(binaryBitmap,hints);

System.err.println("解析结果:"+result.toString());

System.out.println(result.getBarcodeFormat());

System.out.println(result.getText());

}

}

上一篇下一篇

猜你喜欢

热点阅读