java實現二維碼生成

weixin_33816300發表於2018-06-06

二維碼:

12519002-1440316f17d172d9.png

使用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());

}

}

相關文章