我们采用google的zxing包来生成和解析二维码,pom依赖如下:
<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>
测试代码:
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.nio.file.Path;
import java.util.HashMap;
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;
public class TestQRCode {
public static void main(String[] args) {
generate();
decode();
}
/**
* 生成二维码
*/
public static void generate() {
int width = 300;
int height = 300;
String format = "png";
String contents = "http://www.xxx.com/card/plant/auth/exchange?userId=297";
HashMap map = new HashMap(3);
map.put(EncodeHintType.CHARACTER_SET, "UTF-8");
map.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.M);
map.put(EncodeHintType.MARGIN, 0);
try {
BitMatrix bm = new MultiFormatWriter().encode(contents, BarcodeFormat.QR_CODE, width, height, map);
Path file = new File("E:/qrcode.png").toPath();
MatrixToImageWriter.writeToPath(bm, format, file);
System.out.println("==========生成二维码成功==========");
} catch (WriterException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* 解码
*/
public static void decode() {
try {
MultiFormatReader reader = new MultiFormatReader();
File f = new File("E:/qrcode.png");
BufferedImage image = ImageIO.read(f);
BinaryBitmap binaryBitmap = new BinaryBitmap(new HybridBinarizer(new BufferedImageLuminanceSource(image)));
HashMap map = new HashMap(1);
// 解析复杂二维码
map.put(DecodeHintType.PURE_BARCODE, Boolean.TRUE);
map.put(EncodeHintType.CHARACTER_SET, "utf-8");
Result result = reader.decode(binaryBitmap, map);
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();
}
}
}
如果你对JAVA有其它任何问题,欢迎加入JAVA交流探讨群。
微信回复加群,拉你进群;微信回复面试,得到最新大厂面试资料。