解决方案:
pom引入
<dependency>
<groupId>com.google.zxing</groupId>
<artifactId>core</artifactId>
<version>3.4.1</version>
</dependency>
<dependency>
<groupId>com.google.zxing</groupId>
<artifactId>javase</artifactId>
<version>3.4.1</version>
</dependency>
- 生成二维码
@Test
void test() {
int width = 300;
int hight = 300;
String format = "png";
String content = "测试Demo";
// 定义二维码参数
HashMap<EncodeHintType, Object> 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, hight, map);
Path file = new File("D:\\image.png").toPath();
MatrixToImageWriter.writeToPath(bitMatrix, format, file);
} catch (Exception e) {
e.printStackTrace();
}
}
- 读取二维码
@Test
void test() {
MultiFormatReader multiFormatReader = new MultiFormatReader();
File file = new File("D:\\image.png");
try {
BufferedImage image = ImageIO.read(file);
LuminanceSource luminanceSource = new BufferedImageLuminanceSource(image);
Binarizer binarizer = new HybridBinarizer(luminanceSource);
BinaryBitmap binaryBitmap = new BinaryBitmap(binarizer);
// 定义二维码参数
Map<DecodeHintType, Object> hints = new HashMap<>();
hints.put(DecodeHintType.CHARACTER_SET, "utf-8");
Result result = multiFormatReader.decode(binaryBitmap, hints);
System.out.println(result.toString());
System.out.println(result.getBarcodeFormat());
System.out.println(result.getText());
} catch (Exception e) {
e.printStackTrace();
}
}