1、maven依赖
<!-- zxing QrCode -->
<dependency>
<groupId>com.google.zxing</groupId>
<artifactId>core</artifactId>
<version>3.2.1</version>
</dependency>
<dependency>
<groupId>com.google.zxing</groupId>
<artifactId>javase</artifactId>
<version>3.2.1</version>
</dependency>
2、代码如下
package com.yealink.version.util;
import com.google.zxing.*;
import com.google.zxing.client.j2se.BufferedImageLuminanceSource;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.common.HybridBinarizer;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.nio.file.Path;
import java.util.HashMap;
import java.util.Map;
/**
* Created by yl1794 on 2018/6/4.
*/
public class QrCodeUtil {
public static void CreateQrCode(String content, String path){
int width = 300;
int height = 300;
String format = "png";
//定义二维码的参数
HashMap map = new HashMap();
//设置编码
map.put(EncodeHintType.CHARACTER_SET, "utf-8");
//设置纠错等级
map.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.M);
map.put(EncodeHintType.MARGIN, 2);
try {
//生成二维码
BitMatrix bitMatrix = new MultiFormatWriter().encode(content, BarcodeFormat.QR_CODE, width, height);
Path file = new File(path).toPath();
MatrixToImageWriter.writeToPath(bitMatrix, format, file);
} catch (WriterException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public static void ReadQrCode(String path){
try {
MultiFormatReader multiFormatReader = new MultiFormatReader();
File file = new File(path);
BufferedImage image = ImageIO.read(file);
//定义二维码参数
Map hints = new HashMap();
hints.put(EncodeHintType.CHARACTER_SET,"utf-8");
//获取读取二维码结果
BinaryBitmap binaryBitmap = new BinaryBitmap(new HybridBinarizer(new BufferedImageLuminanceSource(image)));
Result result = multiFormatReader.decode(binaryBitmap, hints);
System.out.println("读取二维码: " + result.toString());
System.out.println("二维码格式: " + result.getBarcodeFormat());
System.out.println("二维码内容: " + result.getText());
} catch (NotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public static void main(String[] args){
CreateQrCode("http://127.0.0.1:8890/api/v1/version/get/3a345d5144da45d79d9f195f1e07d364","E:\\QrCode\\test.png");
ReadQrCode("E:\\QrCode\\test.png");
}
}
3、运行结果